The Number()
constructor is used to create a number object. The number object contains a few helpful properties and methods like the isNaN and the toFix method. Here’s an example using the Number()
constructor with the new
keyword:
const myNum = new Number("34");
console.log(typeof myNum); // "object"
In this example we pass in a string literal to the Number()
constructor and the return type is of type object
instead of a string
.
When the Number()
constructor is called as a function without the new
keyword, then the return value will be the primitive number type. Most of the time you will be using the Number()
constructor to convert other data types to the number data type. Here’s an example of converting a string to a number:
const myNum = Number("100");
console.log(myNum); // 100
console.log(typeof myNum); // number
This is helpful when you are getting input from the user and you need to convert that string input to a number so you can perform mathematical calculations.
If you try to call the Number()
constructor through an empty string then the result will be the number 0
:
const num = Number("");
console.log(num); // 0
This is because JavaScript will try to parse the string and since it doesn’t contain any digits, the result will be zero.
If you try to pass in a string with random characters then the result will be NaN
or “Not a Number”.
const num = Number("random");
console.log(num); // NaN
When working with booleans, true
returns 1
because true
gets converted to one and false
returns 0
because false
is converted to zero.
const boolTrue = Number(true);
const boolFalse = Number(false);
console.log(boolTrue); // 1
console.log(boolFalse); // 0
If you pass in null
, the result will be 0
and if you pass undefined
, the result will be NaN
.
const undefinedNum = Number(undefined);
const nullNum = Number(null);
console.log(undefinedNum); // NaN
console.log(nullNum); // 0
When working with arrays there are a few things to consider, an empty array will return 0
, an array with a single number will return that number, an array with multiple numbers returns NaN
, and an array with strings will return undefined
.
const obj1 = Number({});
const obj2 = Number({2: 2});
const obj3 = Number({key: "val"});
const obj4 = Number({key: true});
console.log(obj1); // NaN
console.log(obj2); // NaN
console.log(obj3); // NaN
console.log(obj4); // NaN
When working with objects, the result is always NaN
.
In conclusion, you’ll mostly use the Number()
constructor for type conversion more than creating a number or a number object.