Chapters

FundamentalsChapter 12 of 21

Arithmetic

Doing sums, including the two operators people forget.

The basics

JavaScript

JavaScript

console.log(10 + 3);
console.log(10 - 3);
console.log(10 * 3);
console.log(10 / 3);

Output

13
7
30
3.3333333333333335

Division always produces a fraction. There is no separate integer division, and the trailing digits in that last line are not a bug: they are how binary floating point stores a third, covered in its own chapter.

Remainder

% gives what is left over after division. It is how you test for even numbers, wrap a value round, or split something into groups.

JavaScript

JavaScript

console.log(10 % 3);
console.log(10 % 2 === 0);
console.log((14 + 5) % 12);

Output

1
true
7

That last line is clock arithmetic: five hours after 14 o clock is 7. With negatives it keeps the sign of the left side, so -7 % 3 is -1.

Exponent

JavaScript

JavaScript

console.log(2 ** 10);
console.log(9 ** 0.5);

Output

1024
3

Increment and decrement

++ and -- change a variable by one. Their position matters: before the name returns the new value, after it returns the old one.

JavaScript

JavaScript

let count = 5;

console.log(count++);
console.log(count);
console.log(++count);

Output

5
6
7

Tip

That distinction has caused enough confusion that plenty of teams use count += 1 everywhere instead. It says the same thing and never depends on where the operator sits.

Order

Exponent binds tightest, then multiply, divide and remainder, then add and subtract. Left to right within a level.

JavaScript

JavaScript

console.log(2 + 3 * 4 ** 2);
console.log(100 / 10 / 2);

Output

50
5

When arithmetic gives NaN

An operation that cannot produce a number produces NaN, which stands for not a number and is itself of type number.

JavaScript

JavaScript

console.log('abc' * 2);
console.log(typeof NaN);
console.log(NaN === NaN);
console.log(Number.isNaN(NaN));

Output

NaN
number
false
true

NaN is the only value in JavaScript that is not equal to itself, so test for it with Number.isNaN rather than ===.

Test yourself

3 questions

What does 10 % 3 produce?

Show the answer

1 The remainder after dividing, which is what makes it useful for even and odd tests.

Why does NaN === NaN return false?

Show the answer

NaN is defined as not equal to anything, including itself Use Number.isNaN, which was added precisely because the comparison cannot work.

What does count++ return?

Show the answer

The value before the increment The prefix form ++count returns the new value instead, which is the whole difference.

Next chapter

Assignment

Storing values, and the shorthand forms worth knowing.