Number in JavaScript
The Number Type in JavaScript
In JavaScript, numbers are uniformly represented by the number type, which encompasses integers, fractions, positive, negative, and special numeric values. Unlike many programming languages, JavaScript does not differentiate between int, float, or double.
All numbers in JavaScript are stored as 64-bit floating-point values according to the IEEE 754 standard. This means even integers are technically floats.
let int = 42;
let float = 3.14;
let negative = -100;
typeof and Recognizing the Number Type
typeof 42; // 'number'
typeof 3.14; // 'number'
typeof NaN; // 'number'
typeof Infinity; // 'number'
Even NaN and Infinity are considered numbers.
Value | Description |
NaN | Result of an invalid mathematical operation |
Infinity | Infinitely large number |
-Infinity | Infinitely small number |
Number.MAX_VALUE | Largest representable number |
Number.MIN_VALUE | Smallest (non-negative) representable number |
Number.MAX_SAFE_INTEGER | 2^53 - 1 |
Number.MIN_SAFE_INTEGER | -(2^53 - 1) |
Number.EPSILON | Smallest difference between 1 and the next representable number |
NaN === NaN; // false (!)
isNaN(NaN); // true
Number.isNaN(NaN); // true
Boolean(0); // false
Boolean(NaN); // false
Boolean(42); // true
Boolean(-1); // true
Number("42"); // 42
Number("3.14"); // 3.14
Number("abc"); // NaN
parseInt("42px"); // 42
parseFloat("3.14m"); // 3.14
'5' + 1; // "51"
'5' - 1; // 4
true + 1; // 2
null + 1; // 1
undefined + 1; // NaN
let n = 123.456;
n.toFixed(2); // "123.46"
n.toPrecision(4); // "123.5"
n.toExponential(1); // "1.2e+2"
Math.PI; // 3.14159...
Math.round(4.7); // 5
Math.floor(4.9); // 4
Math.ceil(4.1); // 5
Math.pow(2, 3); // 8
Math.sqrt(9); // 3
Math.random(); // random number between 0 and 1
Math.max(1, 5, 10); // 10
Math.min(1, 5, 10); // 1
If you need to work with numbers larger than Number.MAX_SAFE_INTEGER, use BigInt.
Numeric values in JavaScript are primitives. However, when methods like toFixed or toString are called on them, JavaScript temporarily converts them to a Number object internally.
let n = 42;
n.toFixed(2); // "42.00"
In the example above, n is a primitive, but JavaScript implicitly performs:
new Number(42).toFixed(2);
This is called autoboxing. It allows numbers to retain their lightweight primitive nature while still accessing object-like functionality.
You can explicitly create a Number object, but this is generally discouraged:
let n1 = 42;
let n2 = new Number(42);
console.log(typeof n1); // "number"
console.log(typeof n2); // "object"
console.log(n1 === n2); // false
Conclusion: Use primitive numbers for most cases, and reserve Number objects for special scenarios.