In JavaScript, the Number() function is used to convert a value to a number. It can convert a wide range of data types, including strings, objects, booleans, and even 'null' or 'undefined', into their corresponding numeric representations.
Syntax:
Number(value)
- value: The value to be converted to a number.
Examples:
1. Convert a String to a Number:
let strNumber = "42"; let num = Number(strNumber); console.log(num); // Output: 42
2. Convert a Boolean to a Number:
let boolValue = true; let num = Number(boolValue); console.log(num); // Output: 1
3. Convert `null` to a Number:
let nullValue = null; let num = Number(nullValue); console.log(num); // Output: 0
4. Convert an Object to a Number:
let obj = { key: "value" };
let num = Number(obj);
console.log(num); // Output: NaN (Not-a-Number)
Explanation:
- When Number() is called with a string, it tries to parse the string as a numeric value. If the string contains a valid number, it returns that number. Otherwise, it returns 'NaN'.
- When Number() is called with a boolean, it returns '1' for 'true' and '0' for 'false'.
- When Number() is called with 'null', it returns '0'.
- When Number() is called with an object, it returns 'NaN' because objects cannot be directly converted to numbers.
Code Compiler Link: https://app.singhteekam.in/codecompiler/