Skip to content
Tutorials Center
My learning

Topics

JavaScript Reference ยท Number and BigInt

The Number() function

Reference for JavaScript Number(): how strings, booleans, null, undefined, arrays, dates and BigInts convert to numbers, plus NaN results and new Number().

Number() called as a plain function converts any value to a number primitive. It is the strict, whole-value converter: the entire string must look like a number, otherwise the result is NaN. That makes it different from parseInt() and parseFloat(), which read as much as they can from the start of a string.

Number is also the name of the built-in object that holds constants such as Number.EPSILON and helpers such as Number.isInteger(). This page covers the conversion call.

JavaScript
Number("42");     // 42
Number("42px");   // NaN
Number(true);     // 1

Try it

JS What converts to what

Press Run (or Ctrl + Enter) to see the console output here.

No output.

JS BigInt, Symbol and the wrapper object

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Syntax

JavaScript
Number(value)
Number()
new Number(value)
Name Description
value Optional. The value to convert. With no argument the result is 0.

Return value: a number primitive when called as a function. With new, a Number wrapper object (avoid this).

Exceptions: a TypeError for a Symbol, or when an object's conversion method throws.

Usage notes

  • Strings: surrounding whitespace is ignored. An empty or whitespace-only string gives 0, not NaN, which surprises many people. Decimal, exponent ("1e3"), 0x, 0o and 0b forms are accepted; a sign is allowed only on decimal text. "Infinity" converts to Infinity.
  • Not accepted: thousands separators, numeric separators ("1_000"), units, or trailing text. All give NaN.
  • Other primitives: true is 1, false and null are 0, undefined is NaN.
  • Objects are first converted to a primitive. An empty array becomes "", so Number([]) is 0; [7] becomes "7"; [1, 2] becomes "1,2", which is NaN. A Date converts to its timestamp in milliseconds.
  • BigInt: Number(10n) works, but values beyond Number.MAX_SAFE_INTEGER lose precision. The unary + operator does not accept a BigInt and throws.
  • Check the result: Number.isNaN(result) tells you the conversion failed. Do not compare with === NaN.
  • Do not use new Number(). It returns an object, which breaks === comparisons and is truthy even when it wraps 0.
  • Passing Number to map() works because it ignores extra arguments, unlike parseInt.

Browser support

Number() conversion is available in every browser and JavaScript runtime. Support for the 0b and 0o string forms came with ES2015 and is universal in current engines.