Don't run away! We promise this is the fun kind of math, where the computer does all the hard work and you just take the credit.
An operator is a symbol that does something to values. You've already used a few: + to add, * to multiply, = to assign. Here's the full set of math operators:
| Operator | Name | Example | Result |
|---|---|---|---|
+ | Addition | 7 + 3 | 10 |
- | Subtraction | 7 - 3 | 4 |
* | Multiplication | 7 * 3 | 21 |
/ | Division | 7 / 2 | 3.5 |
% | Remainder | 7 % 3 | 1 |
** | Exponent (power) | 2 ** 3 | 8 |
The values on either side of an operator are called operands. So in 7 + 3, the operator is + and the operands are 7 and 3. (You don't need to remember that word, but it'll make you sound very smart at dinner.)
const a = 17;
const b = 5;
console.log(a + b);
console.log(a - b);
console.log(a * b);
console.log(a / b);
console.log(a % b);
console.log(b ** 2);
It prints
22 12 85 3.4 2 25
The remainder operator %
The one that's new to most people is %, the remainder operator (sometimes called "modulo" or "mod"). It gives you what's left over after dividing.
You have 17 slices of pizza to share between 5 friends. Everybody gets 3 slices (that's 15 slices), and there are 2 slices left over. So 17 % 5 is 2. The remainder is what nobody gets. (Except you. You get the leftovers. Chef's privilege.)
The remainder operator is surprisingly useful. The most common trick is checking whether a number is even or odd. Even numbers divide by 2 with nothing left over:
console.log(10 % 2);
console.log(7 % 2);
console.log(0 % 2);
It prints
0 1 0
If number % 2 is 0, the number is even. If it's 1, the number is odd. You'll use this trick all the time, especially in Grade 5 with loops.
The exponent operator **
** raises a number to a power. 2 ** 3 means "2 times itself 3 times": 2 × 2 × 2 = 8. And 10 ** 6 is a million. Handy for science, compound interest, and calculating how many lines of code you'll have written by the end of this book.