JavaScript · Unit 1: JavaScript basics · Lesson 3 of 5
Numbers and math
JavaScript does math with + and -, * to multiply and / to divide.
Opens this lesson in Code Academy. Lessons open one after another, and each unit opens when you pass the checkpoint quiz before it (you can take a checkpoint early to skip ahead). If this lesson is not open yet, the button shows you its unit on your map.
The idea
JavaScript does math with + and -, * to multiply and / to divide. % gives the remainder: 7 % 3 is 1.
Multiplication and division happen before addition and subtraction, as in school math. Parentheses choose the order: (2 + 3) * 4 is 20.
Decimals work, but some, like 0.1 + 0.2, come out as 0.30000000000000004 because computers store them in binary. Round money before you show it.
Worked example
JavaScript
const price = 12;
const qty = 3;
console.log(price * qty);
console.log(2 + 3 * 4);
console.log((2 + 3) * 4);
console.log(10 % 4);
It prints
36
14
20
2
Key terms
- Operators
- + - * / and % (remainder). Multiplication and division happen first unless parentheses say otherwise.
Practise it in Code Academy
It has 4 exercises (predict the output, fill in the blank, fix the broken code and write code from a prompt) and takes about 6 minutes. Every answer is checked as you go, and feedback names the exact mistake. Hints and the solution are there if you get stuck.
Every lesson is free: no ads, no lives and no paywall.