Numbers, Math, and Randomness
Understand how JavaScript really counts, dodge the classic number bugs, and build a fun guessing game.
- explain why JavaScript has just one kind of number,
- understand why
0.1 + 0.2is not exactly0.3, - round numbers safely and handle money without bugs,
- recognise
NaNand check for it correctly, - use the
Mathobject and generate random numbers in a range, - put it all together in a number-guessing game.
One number type to rule them all
Many languages have two separate kinds of numbers: integers (whole numbers like 7) and floating-point numbers (decimals like 3.14). JavaScript, the language Node runs, keeps things simple on the surface: there is just one number type, called number. Whether you write 7 or 3.14, Node stores both as the same kind of value - a 64-bit floating-point number.
Analogy. Imagine a ruler that can measure any length, but its smallest marks are tiny fixed steps. Whole centimetres land exactly on a mark, so they are perfectly precise. But a length like "one third of a centimetre" falls between two marks, so the ruler has to pick the nearest mark - close, but not perfect. JavaScript numbers work the same way: whole numbers up to a very large size are exact, but many decimals can only be stored as the nearest available value.
You can check the type of any value with typeof:
typeof 7 // "number"
typeof 3.14 // "number"
typeof -0.5 // "number"
All three are the same type. There is no separate "int" or "float" - just number. This makes beginner code simpler, but it is also the root of the surprises we will meet next.