Arithmetic operators
Your first calculator lived in a classroom. JavaScript's lives in every app you use: prices, scoreboards, progress bars. Let's start there.
They are used to do calculations with numbers. They are the same ones you use in math, with a few additions specific to programming.
| Operator | Name | Example | Result |
|---|---|---|---|
+ |
Addition | 5 + 2 |
7 |
- |
Subtraction | 5 - 2 |
3 |
* |
Multiplication | 5 * 2 |
10 |
/ |
Division | 5 / 2 |
2.5 |
% |
Remainder (modulo) | 5 % 2 |
1 |
** |
Power | 5 ** 2 |
25 |
The remainder (%) is not the division
The % operator returns what is left over from an integer division. Think about
sharing out candy: if you have 7 pieces of candy between 2 children, each one gets 3 and
1 is left over. That 1 is 7 % 2.
console.log(7 % 2); // 1 (1 left over)
console.log(8 % 2); // 0 (even: nothing left over)
console.log(9 % 3); // 0
That is why number % 2 === 0 is the classic way to tell whether a number is even.
Assignment operators
Once you have a variable, you can update it with shortcuts:
let points = 10;
points += 5; // equivalent to: points = points + 5 → 15
points -= 3; // → 12
points *= 2; // → 24
Increment and decrement
++ adds 1 and -- subtracts 1. They are very common in loops:
let counter = 0;
counter++; // now it equals 1
counter++; // now it equals 2
With this you can already move numbers around at will. In the next lesson we stop calculating and start comparing: the first step toward making your code decide.
Examples
Basic calculations
const a = 17;
const b = 5;
console.log("sum:", a + b);
console.log("remainder:", a % b);
console.log("power:", b ** 2);
Assignment shortcuts
let balance = 100;
balance += 50; // deposit
balance -= 30; // expense
console.log("final balance:", balance);