Summary
In JavaScript, you have the following basic arithmetic operators:
- Addition: +
- Subtraction: –
- Multiplication: *
- Division: /
- Remainder: %
- Exponential: **
Details
Most of these should look familiar, except for the remainder operator. The remainder operator returns the remainder after dividing. For example, 3 % 2
would return 1
.
Here are some more examples of all of the operators:
const addition = 3 + 3; // 6
const subtraction = 3 - 3; // 0
const multiplication = 3 * 3; // 9
const division = 3 / 3; // 1
const remainder = 3 % 3; // 0
const exponential = 3 ** 3; // 3 * 3 * 3 = 27
Order of operations
The order of operations in JavaScript is the same order you were taught in school. Exponents get calculated first, then multiplication and division (from left to right), and then addition and subtraction (from left to right). You can override this order by using parentheses.
In the first example below, the multiplication is evaluated first, then the addition and subtraction. In the second example, the expressions in parentheses are evaluated first, then the multiplication.
1 + 2 * 3 - 4 // Output is 3
(1 + 2) * (3 - 4) // Output is -3
Demo
Exercises
Try the following statements in the console:
1 + 1
1 - 1
2 * 2
2 / 2
3 % 2
3 ** 2
The answers should be 2, 0, 4, 1, 1, and 9.
References
Numerical literals on MDN
Arithmetic operators on MDN
Operator precedence on MDN
Operator precedence table on MDN