JS: Number Constructor

By Xah Lee. Date: . Last updated: .

〔►see JS: Number Object

// Number called as function, return a number primitive value
console.log ( ( typeof Number(3) ) === "number" ); // true

// Number called as constructor, returns a number object
console.log ( ( typeof (new Number(3)) ) === "object" ); // true

console.log ( Number(3) === (new Number(3)) ); // false

〔►see JS: Data Types

var n = new Number(3);

console.log( typeof n === "object" ); // true
console.log( typeof 3 === "number" ); // true

console.log ( n.valueOf ( ) === 3 ); // true

Convert to Number

Argument TypeResult
undefinedReturn NaN.
nullReturn +0.
true or falseReturn 1 if argument is true. Return +0 if argument is false.
NumberReturn argument (no conversion).
StringReturn a number or NaN.
SymbolThrow a TypeError exception.
ObjectReturn a number or NaN

Special literal values of number.

// these are literal values of number type. No conversion is done.
console.log ( Number (Infinity) === Infinity ); // true
console.log ( Number (-Infinity) === -Infinity ); // true

console.log ( Number (-Infinity) === Infinity ); // false

console.log (
 Number.isNaN ( Number (NaN) )
); // true

// NaN === NaN is false

Convert special literal values to number.

console.log ( Number.isNaN (
 Number (undefined)
 ) ); // true

console.log ( Number (null) === 0 ); // true

console.log ( Number (true) === 1 ); // true
console.log ( Number (false) === 0 ); // true

Convert string to number.

console.log ( Number ("0.03") === 0.03 ); // true

// extra zero before or after is ok
console.log ( Number ("00.03") === 0.03 ); // true
console.log ( Number ("00.030") === 0.03 ); // true

// extra space in front or back are ok
console.log ( Number ("  0.03  ") === 0.03 ); // true
console.log ( Number ("  +0.03  ") === 0.03 ); // true
console.log ( Number ("  -0.03  ") === -0.03 ); // true

// cannot have space after sign
console.log ( Number ("- 0.03 ") ); // NaN

// cannot have space between digits
console.log ( Number ("1 000")  ); // NaN

Reference

ECMAScript® 2016 Language Specification#sec-number-constructor

Number Topic


  1. JS: Number Object
  2. JS: Number Constructor
  3. JS: Number.prototype
Like what you read? Buy JavaScript in Depth