Arithmetic operators are used to perform mathematical calculations on numbers (literals or variables). From simple addition to complex power calculations, JavaScript provides a full set of tools to handle math inside your code.
Here are the most common arithmetic operators you will use in JavaScript:
| Operator | Description | Example |
|---|---|---|
+ |
Addition | x + y |
- |
Subtraction | x - y |
* |
Multiplication | x * y |
** |
Exponentiation (ES2016) | x ** y |
/ |
Division | x / y |
% |
Modulus (Division Remainder) | x % y |
++ |
Increment | x++ or ++x |
-- |
Decrement | x-- or --x |
In a mathematical expression, the numbers are called operands and the symbol representing the action is called the operator.
In the expression 10 + 5:
10 and 5 are operands.+ is the operator.The addition operator adds numbers together.
let x = 10;
let y = 5;
let result = x + y; // result is 15
The subtraction operator subtracts the second number from the first.
let x = 10;
let y = 5;
let result = x - y; // result is 5
The multiplication operator multiplies two numbers.
let x = 10;
let y = 5;
let result = x * y; // result is 50
The exponentiation operator raises the first operand to the power of the second operand.
let x = 5;
let result = x ** 2; // result is 25 (5 squared)
The division operator divides the first number by the second.
let x = 10;
let y = 2;
let result = x / y; // result is 5
The modulus operator returns the remainder of a division. It is often
used to check if a number is even or odd (e.g., x % 2 === 0).
let x = 10;
let y = 3;
let result = x % y; // result is 1 (10 divided by 3 leaves a remainder of 1)
The increment operator increases a number by 1.
let x = 5;
x++;
// x is now 6
The decrement operator decreases a number by 1.
let x = 5;
x--;
// x is now 4
Operator precedence describes the order in which operations are performed in an arithmetic expression. Just like in school math, multiplication and division are performed before addition and subtraction (PEMDAS/BODMAS).
let result = 100 + 50 * 3; // result is 250, because 50 * 3 is done first
You can use parentheses () to force a different order of
calculation:
let result = (100 + 50) * 3; // result is 450, because the addition happens first
% is great for finding remainders** is a modern way to calculate powers++ and decrement -- are shortcuts to change
values by 1