The basics of syntax

INPUT · Slides

Dividing, and what is left over

01 / 06

Divide with /

Division uses / (a forward slash). ÷ will not work.

console.log(20 / 4);

Result

5

02 / 06

It goes decimal when it does not divide evenly

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

The remainder is %

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

% tells you whether it divided evenly

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

Dividing by zero gives you something odd

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

Learn / and % as a pair

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 in

Sharing 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