Step 1 of 8 · Reading · ~3 min
Learn
Getting Started
Numbers and Math
By the end of this lesson you can do whole-number arithmetic correctly in JavaScript, split a quantity into units with % and rounding, and avoid the two number traps that catch everyone: floating-point error and NaN.
One number type
JavaScript has a single kind of ordinary number: a 64-bit floating-point value. There is no separate integer type, so 7 and 7.0 are the same value.
% gives the remainder after division: 7 % 3 is 1 because 7 = 2 x 3 + 1. It is the tool for "what is left over" and for wrapping around, such as a weekday after adding days.
Whole-number division
There is no integer-division operator. Divide, then round with a Math function:
For positive numbers floor and trunc agree; for negatives they do not, so pick the one you mean.
Splitting a quantity into units
Math.floor(x / size) counts how many whole units fit, and x % size is what remains. For 275 cents:
When there are several units (weeks, days, hours), peel them off from largest to smallest, and each time continue with the remainder you have left.
Precedence
*, / and % bind tighter than + and -, exactly as in school maths. Use parentheses whenever the order matters: a + b / 2 divides only b, while (a + b) / 2 averages.
Floats are approximate
Computers store most decimals in binary, so some are slightly off:
=== asks whether two values are equal and gives true or false; the conditionals lesson covers comparisons fully.
Never test floats for equality. Compare with a tolerance, Math.abs(a - b) < 1e-9, or keep money in whole cents (integers are exact up to 9,007,199,254,740,991, Number.MAX_SAFE_INTEGER).
Special values and parsing
Number(text) demands the whole text be a number, so it gives NaN for "12px". parseInt(text, 10) reads leading digits and stops at the first other character. Always pass 10 as the second argument so the base is explicit.
For integers beyond 2^53 there is a separate type, BigInt (12345678901234567890n); it cannot be mixed with ordinary numbers and is covered in the advanced track.
Common mistakes
- Forgetting parentheses:
a + b / 2is not an average. - Mixing a number and a string with
+:1 + 2 + "x"is"3x", but"x" + 1 + 2is"x12"because once a string is involved,+joins. - Dividing without rounding and then printing
3.5or0.3333333333333333when a whole number was expected. - Testing
x === NaN. It is alwaysfalse; useNumber.isNaN(x).
Your exercise
Turn a count of seconds into hours, minutes and seconds. The starter reads the number for you and leaves the three unit variables for you to work out.
Discussion
Ask a question, share an insight, or help someone who’s stuck.
Sign in to post a comment or reply.
Loading…