01 / 06
Divide with /
The basics of syntax
INPUT · Slides
01 / 06
Division uses / (a forward slash). ÷ will not work.
console.log(20 / 4);Result
5
02 / 06
If it does not divide evenly, JS gives you the answer as a decimal.
It will not quietly hand you a remainder the way you were taught at school.
console.log(7 / 2);Result
3.5
03 / 06
When you want what is left over, use %. It hands back the bit that did not divide.
7 divided by 2 is 3 with 1 left over, so 7 % 2 is 1.
console.log(7 % 2);console.log(10 % 5);Result
1 0
04 / 06
If % gives you 0, it divided evenly.
That lets you ask "is this even?" or "is this a multiple of 3?". It earns its keep once you get to branching on a condition.
console.log(8 % 2);console.log(9 % 2);Result
0 1
05 / 06
You were told never to divide by zero. JS does not treat it as an error.
Instead it hands back a special value, Infinity. Nothing stops, which makes the mistake easy to miss, so keep an eye out.
console.log(5 / 0);Result
Infinity
06 / 06
Given the same two numbers, / and % are asking different questions.
/ … how many times does it go in% … how much is left that will not go inSharing 30 sweets between 7 people: / is what each person gets, % is what is left in the bag. Get these two straight and you can write most of the sums that come up in a day.
console.log(30 / 7);console.log(30 % 7);Result
4.285714285714286 2