Numbers and maths
This page needs a recent browser (with SharedArrayBuffer support). Please update Chrome, Edge, Firefox or Safari to the latest version.
Maths like a calculator
- JavaScript does maths with
+-*/. - There is only one kind of number, so
/can give a decimal:7 / 2is3.5.
console.log(7 + 2); // → 9
console.log(7 / 2); // → 3.5
Remainder and powers
%gives the remainder after dividing:23 % 5is3(5 goes in 4 times, 3 left over).**raises to a power:2 ** 5is2 × 2 × 2 × 2 × 2.
console.log(23 % 5); // → 3
console.log(2 ** 5); // → 32
Order of operations
*/%happen before+and-— the same rules as in maths class.- Use brackets
( )to force what should happen first.
Explore
Order of operations, step by step
× and ÷ happen before + and −. Brackets go first of all.
console.log(2 + 3 * 4); // → 14 (the 3 * 4 first)
console.log((2 + 3) * 4); // → 20 (the brackets first)
Common mistakes
%is the remainder operator;/can give a decimal."3" + 4gives"34"(a string), not7.
Now you try
- Use the maths operators.
- Press Check answer to test it.
Log 6 times 7 (it is 42).
Click Run to see the output here.
Use % to log the remainder when 23 is divided by 5 (it is 3).
Click Run to see the output here.
a is 4 and b is 8. Log their average, (a + b) / 2 (it is 6). Use brackets so the addition happens first.
Click Run to see the output here.