Operators
Operators are symbols that perform actions on values: they add, multiply, assign. The result of an operator can be printed or stored in a variable.
What an operator is
An operator sits between values and returns a result. The simplest example is addition:
console.log(7 + 2); // 9Here + is the operator and 7 and 2 are its operands — the values it works on. A combination of values and operators is called an expression.
Arithmetic operators
| Operator | Action | Example | Result |
|---|---|---|---|
+ | Addition | 7 + 2 | 9 |
- | Subtraction | 7 - 2 | 5 |
* | Multiplication | 7 * 2 | 14 |
/ | Division | 7 / 2 | 3.5 |
% | Remainder | 7 % 2 | 1 |
** | Exponentiation | 7 ** 2 | 49 |
Division in JavaScript is always exact: 7 / 2 gives 3.5, not 3.
The remainder
The % operator returns what is left after whole-number division. For example, 3 goes into 7 twice, and 1 is left over:
console.log(7 % 3); // 1The remainder is often used to check whether a number is even: an even number has a remainder of zero when divided by 2.
console.log(10 % 2); // 0
console.log(11 % 2); // 1Operator precedence
As in maths, multiplication and division happen before addition and subtraction:
console.log(2 + 3 * 4); // 14Parentheses change the order:
console.log((2 + 3) * 4); // 20When in doubt about the order, add parentheses: the code becomes clearer to you and to others.
Compound assignment
total = total + 5 can be shortened to total += 5. The other operations have the same shortcuts: -=, *=, /=:
let total = 10;
total += 5;
console.log(total); // 15Compound assignment is handy when a value accumulates: an order total, a game score, the number of attempts.
Increment and decrement
The ++ and -- operators change a variable by one. They are called increment and decrement:
let lives = 3;
lives--;
console.log(lives); // 2You will most often see ++ in loops, where steps need counting.
Common mistake
The + operator not only adds numbers but also joins strings. If at least one value is a string, you get concatenation instead of a sum. The other operators work only with numbers, so they turn the string into a number:
console.log('5' + 3); // 53
console.log('5' - 3); // 2Values from form fields always arrive as strings, so convert them with Number() before adding.