JavaScript ยท Chapter 9 of 55

JavaScript Arithmetic

Arithmetic operators perform mathematical calculations on numbers: addition `+`, subtraction `-`, multiplication `*`, division `/`, modulus `%`, and exponentiation `**`.

JavaScript also supports increment `++` and decrement `--` operators to quickly add or subtract one from a variable.

Basic operations

The five basic arithmetic operators work as in standard math, and `%` returns the remainder of a division.

Increment and decrement

`x++` increases x by 1 (postfix, returns old value), `++x` does the same but returns the new value (prefix). `x--` and `--x` work similarly for decreasing.

Example 1 (javascript)
console.log(10 % 3);
console.log(2 ** 10);
Output
1
1024

Modulus gives the remainder; ** raises to a power.

Example 2 (javascript)
let count = 5;
count++;
console.log(count);
Output
6

Increment adds 1 to the variable.

Key points

  • `%` returns the remainder of division.
  • `**` raises a number to a power.
  • `++` and `--` increment/decrement by one.
  • Division `/` always returns a floating-point result if not evenly divisible.
๐Ÿ’ก Note: Be careful with floating-point math โ€” `0.1 + 0.2` does not exactly equal `0.3` due to binary representation.

๐Ÿ“ Quick Quiz

1. What does `10 % 3` return?

2. Which operator raises a number to a power?

3. What does `x++` do?