Numbers and math in JavaScript
Topic 3 of 64 · 8 minFree lessonJavaScript is a calculator that never gets tired. Prices, scores, distances and times are all numbers, and you'll work them out with a few symbols you mostly know already.
The four basic sums
JavaScript uses + and - as usual. For times it uses *, and for divided by it uses /.
console.log(7 + 3);console.log(7 - 3);console.log(7 * 3);console.log(7 / 2);JavaScript has one kind of number for whole numbers and decimals alike. So 7 / 2 gives 3.5, with nothing cut off.
Which part goes first
As in school math, * and / happen before + and -. Use brackets when you want a part worked out first.
console.log(2 + 3 * 4);console.log((2 + 3) * 4);Remainders and powers
The % sign gives the remainder: what's left over after dividing. It's handy for checking if a number is even. The ** sign raises a number to a power, so 2 ** 3 means 2 times 2 times 2.
console.log(17 % 5);console.log(10 % 2);console.log(2 ** 3);17 divided by 5 is 3, with 2 left over. 10 divided by 2 leaves nothing, so 10 is even.
Short ways to change a variable
Changing a variable by some amount is so common that it has short forms. += adds to a variable, and -= takes away from it. ++ adds exactly one.
let points = 10;points += 5;points -= 2;points++;console.log(points);Each line changes points in turn: 10 becomes 15, then 13, then 14.
Small surprises with decimals
Computers store decimals in a way that isn't always exact. Once in a while, a tiny error shows up at the end.
console.log(0.1 + 0.2);This happens in almost every programming language, not only JavaScript. When you show money or measurements, you'll round the answer. You'll learn how in a later topic.
NaN, which means "Not a Number". If you see NaN, look for a value that isn't the number you expected.console.log("apple" * 3);pricePerKilo and kilos. Then a sum like pricePerKilo * kilos explains itself.Try it yourself
Run the code in the editor and answer 8 practice questions on numbers and math. It's free, you only need an account.