Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Contents

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); // 9

Here + 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

OperatorActionExampleResult
+Addition7 + 29
-Subtraction7 - 25
*Multiplication7 * 214
/Division7 / 23.5
%Remainder7 % 21
**Exponentiation7 ** 249

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); // 1

The 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); // 1

Operator precedence

As in maths, multiplication and division happen before addition and subtraction:

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

Parentheses change the order:

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

When 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); // 15

Compound 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); // 2

You 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); // 2

Values from form fields always arrive as strings, so convert them with Number() before adding.

Thanks for reading!

Donate to the site — we work hard for you.