++
) and decrementing (
)NaN
NaN
NaN
in ArraysInfinity
Infinity
as a default valueInfinity
b32()
: displaying 32bit integers in binary notationNumber
Number
Number.prototype
This chapter covers JavaScript’s single type for numbers, number
.
You can express both integers and floating point numbers in JavaScript:
However, there is only a single type for all numbers: They are all doubles, 64bit floating point numbers implemented according to the IEEE Standard for FloatingPoint Arithmetic (IEEE 754).
Integers are simply floating point numbers without a decimal fraction:
Note that, under the hood, most JavaScript engines are often able to use real integers, with all associated performance and storage size benefits.
Let’s examine literals for numbers.
Several integer literals let you express integers with various bases:
// Binary (base 2)
assert.equal(0b11, 3);
// Octal (base 8)
assert.equal(0o10, 8);
// Decimal (base 10):
assert.equal(35, 35);
// Hexadecimal (base 16)
assert.equal(0xE7, 231);
Floating point numbers can only be expressed in base 10.
Fractions:
Exponent: eN
means ×10^{N}
Accessing a property of an integer literal entails a pitfall: If the integer literal is immediately followed by a dot then that dot is interpreted as a decimal dot:
7.toString(); // syntax error
There are four ways to work around this pitfall:
assert.equal(1 + 4, 5); // addition
assert.equal(6  3, 3); // subtraction
assert.equal(2 * 1.25, 2.5); // multiplication
assert.equal(6 / 4, 1.5); // division
assert.equal(6 % 4, 2); // remainder
assert.equal(2 ** 3, 8); // exponentiation
%
is a remainder operator (not a modulo operator) – its result has the sign of the first operand:
Both operators coerce their operands to numbers:
++
) and decrementing (
)The incrementation operator ++
exists in a prefix version and a suffix version. In both versions, it destructively adds one to its operand. Therefore, its operand must be a storage location that can be changed. The decrementation operator 
works the same, but subtracts one from its operand. The next two examples explain the difference between the prefix and the suffix version.
Prefix ++
and prefix 
: change and then return.
let foo = 3;
assert.equal(++foo, 4);
assert.equal(foo, 4);
let bar = 3;
assert.equal(bar, 2);
assert.equal(bar, 2);
Suffix ++
and suffix 
: return and then change.
let foo = 3;
assert.equal(foo++, 3);
assert.equal(foo, 4);
let bar = 3;
assert.equal(bar, 3);
assert.equal(bar, 2);
You can also apply these operators to property values:
And to Array elements:
Exercise: Number operators
exercises/numbersmath/is_odd_test.js
These are three ways of converting values to numbers:
Number(value)
+value
parseFloat(value)
(avoid; different than the other two!)Recommendation: use the descriptive Number()
.
Examples:
assert.equal(Number(undefined), NaN);
assert.equal(Number(null), 0);
assert.equal(Number(false), 0);
assert.equal(Number(true), 1);
assert.equal(Number(123), 123);
assert.equal(Number(''), 0);
assert.equal(Number('123'), 123);
assert.equal(Number('xyz'), NaN);
How objects are converted to numbers can be configured. For example, by overriding .valueOf()
:
Exercise: Converting to number
exercises/numbersmath/parse_number_test.js
Two number values are returned when errors happen:
NaN
Infinity
NaN
NaN
is an abbreviation of “not a number”. Ironically, JavaScript considers it to be a number:
When is NaN
returned?
NaN
is returned if a number can’t be parsed:
NaN
is returned if an operation can’t be performed:
NaN
is returned if an operand or argument is NaN
(to propagate errors):
NaN
NaN
is the only JavaScript value that is not strictly equal to itself:
These are several ways of checking if a value x
is NaN
:
const x = NaN;
assert.equal(Number.isNaN(x), true); // preferred
assert.equal(Object.is(x, NaN), true);
assert.equal(x !== x, true);
In the last line, we use the comparison quirk to detect NaN
.
NaN
in ArraysSome Array methods can’t find NaN
:
Others can:
> [NaN].includes(NaN)
true
> [NaN].findIndex(x => Number.isNaN(x))
0
> [NaN].find(x => Number.isNaN(x))
NaN
Alas, there is no simple rule of thumb, you have to check for each method, how it handles NaN
.
Infinity
When is the error value Infinity
returned?
Infinity is returned if a number is too large:
Infinity is returned if there is a division by zero:
Infinity
as a default valueInfinity
is larger than all other numbers (except NaN
), making it a good default value:
function findMinimum(numbers) {
let min = Infinity;
for (const n of numbers) {
if (n < min) min = n;
}
return min;
}
assert.equal(findMinimum([5, 1, 2]), 1);
assert.equal(findMinimum([]), Infinity);
Infinity
These are two common ways of checking if a value x
is Infinity
:
Exercise: Comparing numbers
exercises/numbersmath/find_max_test.js
Internally, JavaScript floating point numbers are represented with base 2 (according to the IEEE 754 standard). That means that decimal fractions (base 10) can’t always be represented precisely:
> 0.1 + 0.2
0.30000000000000004
> 1.3 * 3
3.9000000000000004
> 1.4 * 100000000000000
139999999999999.98
You therefore need to take rounding errors into consideration when performing arithmetic in JavaScript.
Read on for an explanation of this phenomenon.
Quiz: basic
See quiz app.
All remaining sections of this chapter are advanced.
In JavaScript, computations with numbers don’t always produce precise results. For example:
To understand why, we need to explore how JavaScript represents floating point numbers internally. It uses three integers to do so, as described in tbl. 5.
Component  Size  Integer range 

sign  1 bit  [0, 1] 
fraction  52 bits  [0, 2^{52}−1] 
exponent  11 bits  [−1023, 1024] 
The floating point number represented by these integers is computed as follows:
(–1)^{sign} × 0b1.fraction × 2^{exponent}
To make further discussions easier, we simplify this representation:
The new representation works like this:
mantissa × 10^{exponent}
Let’s try out this representation for a few floating point numbers.
For the integer −123, we mainly need the mantissa:
For the number 1.5, we imagine there being a point after the mantissa. We use a negative exponent to move that point one digit to the left:
For the number 0.25, we move the point two digits to the left:
Representations with negative exponents can also be written as fractions with positive exponents in the denominators:
These fractions help with understanding why there are numbers that our encoding cannot represent:
1/10
can be represented. It already has the required format: a power of 10 in the denominator.1/2
can be represented as 5/10
. We turned the 2 in the denominator into a power of 10, by multiplying numerator and denominator with 5.1/4
can be represented as 25/100
. We turned the 4 in the denominator into a power of 10, by multiplying numerator and denominator with 25.1/3
cannot be represented. There is no way to turn the denominator into a power of 10. (The prime factors of 10 are 2 and 5. Therefore, any denominator that only has these prime factors can be converted to a power of 10, by multiplying both numerator and denominator with enough twos and fives. If a denominator has a different prime factor, then there’s nothing we can do.)To conclude out excursion, we switch back to base 2:
0.5 = 1/2
can be represented with base 2, because the denominator is already a power of 2.0.25 = 1/4
can be represented with base 2, because the denominator is already a power of 2.0.1 = 1/10
cannot be represented, because the denominator cannot be converted to a power of 2.0.2 = 2/10
cannot be represented, because the denominator cannot be converted to a power of 2.Now we can see why 0.1 + 0.2
doesn’t produce a precise result: Internally, neither of the two operands can be represented precisely.
The only way to compute precisely with decimal fractions is by internally switching to base 10. For many programming languages, base 2 is the default and base 10 an option. For example, Java has the class BigDecimal
and Python has the module decimal
. There are tentative plans to add something similar to JavaScript: The ECMAScript proposal “Decimal” is currently at stage 0.
JavaScript doesn’t have a special type for integers. Instead, they are simply normal (floating point) numbers without a decimal fraction:
In this section, we’ll look at a few tools for working with these pseudointegers.
The recommended way of converting numbers to integers is to use one of the rounding methods of the Math
object (which is documented in the next chapter):
Math.floor(n)
: returns the largest integer i
≤ n
Math.ceil(n)
: returns the smallest integer i
≥ n
Math.round(n)
: returns the integer that is “closest” to n
. 0.5 is rounded up. For example:
Math.trunc(n)
: removes any decimal fraction (after the point) that n
has, therefore turning it into an integer.
Tbl. 6 shows the results of these functions for various inputs.
2.9 
2.5 
2.1 
2.1 
2.5 
2.9 


Math.floor 
3 
3 
3 
2 
2 
2 
Math.ceil 
2 
2 
2 
3 
3 
3 
Math.round 
3 
2 
2 
2 
3 
3 
Math.trunc 
2 
2 
2 
2 
2 
2 
These are important ranges of integers in JavaScript:
>>>
): unsigned, [0, 2^{32})This is the range of integers that are safe in JavaScript:
[–2^{53}–1, 2^{53}–1]
An integer is safe if it is represented by exactly one JavaScript number. Given that JavaScript numbers are encoded as a fraction multiplied by 2 to the power of an exponent, higher integers can also be represented, but then there are gaps between them.
For example (18014398509481984 is 2^{54}):
> 18014398509481984
18014398509481984
> 18014398509481985
18014398509481984
> 18014398509481986
18014398509481984
> 18014398509481987
18014398509481988
The following properties of Number
help determine if an integer is safe:
assert.equal(Number.MAX_SAFE_INTEGER, (2 ** 53)  1);
assert.equal(Number.MIN_SAFE_INTEGER, Number.MAX_SAFE_INTEGER);
assert.equal(Number.isSafeInteger(5), true);
assert.equal(Number.isSafeInteger('5'), false);
assert.equal(Number.isSafeInteger(5.1), false);
assert.equal(Number.isSafeInteger(Number.MAX_SAFE_INTEGER), true);
assert.equal(Number.isSafeInteger(Number.MAX_SAFE_INTEGER+1), false);
Exercise: Detecting safe integers
exercises/numbersmath/is_safe_integer_test.js
Let’s look at computations involving unsafe integers.
The following result is incorrect and unsafe, even though both of its operands are safe.
The following result is safe, but incorrect. The first operand is unsafe, the second operand is safe.
Therefore, the result of an expression a op b
is correct if and only if both operands and the result are safe:
JavaScript’s bitwise operators work as follows:
Internally, the operators use the following integer ranges (input and output):
>>>
): 32 bits, range [0, 2^{32})The results of some of these operators are easiest to understand if we display them as unsigned 32bit integers, in binary notation. That’s what b32()
does (whose implementation is shown later):
assert.equal(
b32(1),
'11111111111111111111111111111111');
assert.equal(
b32(1),
'00000000000000000000000000000001');
assert.equal(
b32(2 ** 31),
'10000000000000000000000000000000');
Operation  Name 

num1 & num2 
Bitwise And 
num1  num2 
Bitwise Or 
num1 ^ num2 
Bitwise Xor 
The binary operators (tbl. 7) combine the bits of their operands to produce their results:
> (0b1010 & 0b11).toString(2).padStart(4, '0')
'0010'
> (0b1010  0b11).toString(2).padStart(4, '0')
'1011'
> (0b1010 ^ 0b11).toString(2).padStart(4, '0')
'1001'
Operation  Name 

~num 
Bitwise Not, ones’ complement 
The bitwise Not operator (tbl. 8) inverts each binary digit of its operand:
Operation  Name 

num << count 
Left shift 
num >> count 
Signed right shift 
num >>> count 
Unsigned right shift 
The shift operators (tbl. 9) move binary digits to the left or to the right:
>>
preserves highest bit, >>>
doesn’t:
> b32(0b10000000000000000000000000000010 >> 1)
'11000000000000000000000000000001'
> b32(0b10000000000000000000000000000010 >>> 1)
'01000000000000000000000000000001'
b32()
: displaying 32bit integers in binary notationWe have now used b32()
a few times. The following code is an implementation of it.
/**
* Return a string representing n as a 32bit unsigned integer,
* in binary notation.
*/
function b32(n) {
// >>> ensures highest bit isn’t interpreted as a sign
return (n >>> 0).toString(2).padStart(32, '0');
}
assert.equal(
b32(6),
'00000000000000000000000000000110');
n >>> 0
means that we are shifting n
zero bits to the right. Therefore, in principle, the >>>
operator does nothing, but it still coerces n
to an unsigned 32bit integer:
Tbl. 10 shows what happens if you convert various values to numbers via Number()
.
x 
Number(x) 

undefined 
NaN 
null 
0 
boolean  false → 0 , true → 1 
number  x (no change) 
string  '' → 0 
other → parsed number, ignoring leading/trailing whitespace 

object  configurable (e.g. via .valueOf() ) 
JavaScript has the following arithmetic operators:
Operator  Name  Example  

n + m 
Addition  ES1  3 + 4 → 7 
n  m 
Subtraction  ES1  9  1 → 8 
n * m 
Multiplication  ES1  3 * 2.25 → 6.75 
n / m 
Division  ES1  5.625 / 5 → 1.125 
n % m 
Remainder  ES1  8 % 5 → 3 
8 % 5 → 3 

n ** m 
Exponentiation  ES2016  4 ** 2 → 16 
Operator  Name  Example  

+n 
Unary plus  ES1  +(7) → 7 
n 
Unary negation  ES1  (7) → 7 
v++ 
Increment  ES1  let v=0; [v++, v] → [0, 1] 
++v 
Increment  ES1  let v=0; [++v, v] → [1, 1] 
v 
Decrement  ES1  let v=1; [v, v] → [1, 0] 
v 
Decrement  ES1  let v=1; [v, v] → [0, 0] 
JavaScript has the following bitwise operators:
Operands and results of bitwise operators:
>>>
): 32 bits, range [0, 2^{32})The helper function b32()
for displaying binary numbers is shown earlier in this chapter.
Operator  Name  Example  

i & j 
Bitwise And  ES1  (0b1010 & 0b1100).toString(2) → '1000' 
i  j 
Bitwise Or  ES1  (0b1010  0b1100).toString(2) → '1110' 
i ^ j 
Bitwise Xor  ES1  (0b1010 ^ 0b0011).toString(2) → '1001' 
~i 
Bitwise Not  ES1  ~0b11111111111111111111111111111110 → 1 
Operator  Name  Example  

i << j 
Left shift  ES1  (0b1 << 1).toString(2) → '10' 
i >> j 
Signed right shift  ES1  b32(0b10000000000000000000000000000010 >> 1) 
→ '11000000000000000000000000000001' 

i >>> j 
Unsigned right shift  ES1  b32(0b10000000000000000000000000000010 >>> 1) 
→ '01000000000000000000000000000001' 
JavaScript has the following four global functions for numbers:
isFinite()
isNaN()
parseFloat()
parseInt()
However, it is better to use the corresponding methods of Number
, which have fewer pitfalls: Number.isFinite()
, Number.isNaN()
, Number.parseFloat()
, Number.parseInt()
. They were introduced with ES6 and are discussed below.
Number
.EPSILON: number
^{[ES6]}
The difference between 1 and the next representable floating point number. In general, a machine epsilon provides an upper bound for rounding errors in floating point arithmetic.
.MAX_SAFE_INTEGER: number
^{[ES6]}
The largest integer that JavaScript can represent unambiguously (2^{53}−1).
.MAX_VALUE: number
^{[ES1]}
The largest positive finite JavaScript number.
.MIN_SAFE_INTEGER: number
^{[ES6]}
The smallest integer that JavaScript can represent unambiguously (−2^{53}+1).
.MIN_VALUE: number
^{[ES1]}
The smallest positive JavaScript number. Approximately 5 × 10^{−324}.
.NaN: number
^{[ES1]}
The same as the global variable NaN
.
.NEGATIVE_INFINITY: number
^{[ES1]}
The same as Number.POSITIVE_INFINITY
.
.POSITIVE_INFINITY: number
^{[ES1]}
The same as the global variable Infinity
.
Number
.isFinite(num: number): boolean
^{[ES6]}
Returns true
if num
is an actual number (neither Infinity
nor Infinity
nor NaN
).
.isInteger(num: number): boolean
^{[ES6]}
Returns true
if num
is a number and does not have a decimal fraction.
.isNaN(num: number): boolean
^{[ES6]}
Returns true
if num
is the value NaN
:
.isSafeInteger(num: number): boolean
^{[ES6]}
Returns true
if num
is a number and unambiguously represents an integer.
.parseFloat(str: string): number
^{[ES6]}
Coerces its parameter to string and parses it as a floating point number. For converting strings to numbers, Number()
(which ignores leading and trailing whitespace) is usually a better choice than Number.parseFloat()
(which ignores leading whitespace and illegal trailing characters and can hide problems).
.parseInt(str: string, radix=10): number
^{[ES6]}
Coerces its parameter to string and parses it as an integer, ignoring leading whitespace and illegal trailing characters:
The parameter radix
specifies the base of number to be parsed:
Do not use this method to convert numbers to integers: Coercing to string is inefficient. And stopping before the first nondigit is not a good algorithm for removing the fraction of a number. Here is an example where it goes wrong:
It is better to use one of the rounding functions of Math
to convert a number to an integer:
Number.prototype
.toExponential(fractionDigits?: number): string
^{[ES3]}
Returns a string that represents the number via exponential notation. With fractionDigits
, you can specify, how many digits should be shown of the number that is multiplied with the exponent (the default is to show as many digits as necessary).
Example: number too small to get a positive exponent via .toString()
.
Example: fraction not small enough to get a negative exponent via .toString()
.
.toFixed(fractionDigits=0): string
^{[ES3]}
Returns an exponentfree representation of the number, rounded to fractionDigits
digits.
If the number is 10^{21} or greater, even .toFixed()
uses an exponent:
.toPrecision(precision?: number): string
^{[ES3]}
Works like .toString()
, but prunes the mantissa to precision
digits before returning a result. If precision
is missing, .toString()
is used.
.toString(radix=10): string
^{[ES1]}
Returns a string representation of the number.
Returning a result with base 10:
Returning results with bases other than 10 (specified via radix
):
> 4..toString(2)
'100'
> 4.5.toString(2)
'100.1'
> 255..toString(16)
'ff'
> 255.66796875.toString(16)
'ff.ab'
> 1234567890..toString(36)
'kf12oi'
You can use parseInt()
to convert integer results back to numbers:
Quiz: advanced
See quiz app.