JavaScript numbers
looking at and manipulating numbers in JavaScript
// updated 2025-05-02 07:45
A Number
in JavaScript consists of values on which we can perform arithmetic operations:
- simple integers
- (e.g. -2, -1, 0, 1, 2)
- floating point decimals
- (e.g. 0.36, -25.19111)
- infinity
- (i.e.
Infinity
in JavaScript, when dividing a number by0
)
- (i.e.
- non-number
- (i.e.
NaN
to denote the absence of a number where a number should exist)
- (i.e.
Performing arithmetic on a number and a string
One quirk about JavaScript is that it allows us to perform certain operations with different data types. This often yields some amusing results:
const mixedEquation = '10' + 5
// '105'
When we add a number to a string, we get a string!
However, when we subtract (or multiply or divide) a string from a number, we get a number!
const mixedSub = '10' - 5
// 5
const mixedMul = 2 * '8'
// 16
const mixedDiv = 10 / '4'
// 2.5
Performing arithmetic on a number and a Boolean
Now, how about the crazy idea of performing arithmetic with a number and a Boolean (a value that is either true
or false
)? Well:
true
becomes converted to1
false
becomes converted to0
Thus, we end up with this wonderful "new math":
const crazyTrue = 2 + true
// 3
const crazyFalse = 2 + false
// 2
Many more quirks exist but we should take note of these for now to show how crazy JavaScript can get!