Sub topic 1
One Number Type: How JavaScript Stores Numbers
Prerequisites
This chapter assumes you know basic JavaScript syntax (variables, functions, operators), can run code in a browser console or Node.js, and understand === and typeof.
One Type for Everything
JavaScript has a single Number type for both integers and fractions. Every Number is a 64-bit IEEE 754 double-precision float. It has 1 sign bit, 11 exponent bits, and 52 fraction bits. So typeof 7 and typeof 7.5 both return "number", and 7 === 7.0 is true.
Writing Numeric Literals
console.log(255, 0xff, 0o377, 0b11111111); // 255 255 255 255
console.log(1.5e3, 2e-3); // 1500 0.002
console.log(1_000_000 === 1000000); // trueNumeric separators (_) only make the source easier to read. They do not change the value.
Arithmetic, `**`, and `%`
The operators + - * / behave as expected, and ** raises a number to a power. The % operator is a remainder, not a true modulo. Its result takes the sign of the dividend:
console.log(2 ** 10); // 1024
console.log(-7 % 3); // -1
console.log(((-7 % 3) + 3) % 3); // 2 (true modulo)Comparing Floats
Binary floating point cannot store 0.1 or 0.2 exactly, so small errors build up:
console.log(0.1 + 0.2); // 0.30000000000000004
console.log(0.1 + 0.2 === 0.3); // false
function nearlyEqual(a, b, epsilon = Number.EPSILON) {
return Math.abs(a - b) < epsilon;
}
console.log(nearlyEqual(0.1 + 0.2, 0.3)); // trueNaN, Infinity, and -0
console.log(NaN === NaN); // false
console.log(Number.isNaN(NaN)); // true
console.log(1 / 0, 1 / -0); // Infinity -Infinity
console.log(0 === -0); // true
console.log(Object.is(0, -0)); // falseNaN is the only value that is not equal to itself. Use Number.isNaN to test for it, and use Object.is to tell -0 apart from 0.
The Safe Integer Range
With 52 fraction bits (53 bits of precision), integers stay exact only up to Number.MAX_SAFE_INTEGER, which is 2^53 − 1:
console.log(Number.MAX_SAFE_INTEGER); // 9007199254740991
console.log(9007199254740992 === 9007199254740993); // true
console.log(Number.isSafeInteger(2 ** 53)); // falseAbove this limit, two different integers can end up with the same stored value.
Exercise
Why does -7 % 3 return -1 in JavaScript, and how do you get 2 instead?
Show answer
% is a remainder operator, so its result takes the sign of the dividend (-7). To get a true modulo, use ((-7 % 3) + 3) % 3, which returns 2.
Exercise
A test checks result === NaN and never passes, even when result is NaN. Why, and what is the fix?
Show answer
NaN is never equal to anything, including itself, so the comparison is always false. Use Number.isNaN(result) instead.