JavaScript arithmetic operators are used to perform arithmetic operations on numbers (like variables or literals). An arithmetic operation is performed on 2 numbers typically. These numbers are known as an operand and the operation is done by an operator. Following are some basic JavaScript arithmetic operators:
Operator | Description |
+ | Addition |
– | Subtraction |
* | Multiplication |
** | Exponentiation (ES2016) |
/ | Division |
% | Modulus (Remainder) |
++ | Increment |
— | Decrement |
In the below example 10 and 2 are two operands and * is used as an operator.
10 * 2
Following example shows some JavaScript arithmetic operations:
let x = 7; let y = 3; let z = x + y; // result is 10 let z = x - y; // result is 4 let z = x * y; // result is 21 let z = x / y; // result is 2.3333333333333335 let z = x % y; // result is 1 x++; // result is 8 x--; // result is 6 let z = x ** 2; // result is 49
JavaScript Arithmetic – Operators Precedence
The order of performing operations on arithmetic expression is known as precedence of the operator. It describes the sequence of performing on an arithmetic expression.
15 | / | Division | 10 / 5 |
15 | % | Division Remainder | 10 % 5 |
14 | + | Addition | 10 + 5 |
14 | – | Subtraction | 10 – 5 |
13 | << | Shift left | x << 2 |
13 | >> | Shift right | x >> 2 |
13 | >>> | Shift right (unsigned) | x >>> 2 |
12 | < | Less than | x < y |
12 | <= | Less than or equal | x <= y |
12 | > | Greater than | x > y |
12 | >= | Greater than or equal | x >= y |
12 | in | Property in Object | “PI” in Math |
12 | instanceof | Instance of Object | instanceof Array |
11 | == | Equal | x == y |
11 | === | Strict equal | x === y |
11 | != | Unequal | x != y |
11 | !== | Strict unequal | x !== y |
10 | & | Bitwise AND | x & y |
9 | ^ | Bitwise XOR | x ^ y |
8 | | | Bitwise OR | x | y |
7 | && | Logical AND | x && y |
6 | || | Logical OR | x || y |
5 | ?? | Nullish Coalescing | x ?? y |
4 | ? : | Condition | ? “Yes” : “No” |
3 | += | Assignment | x += y |
3 | /= | Assignment | x /= y |
3 | -= | Assignment | x -= y |
3 | *= | Assignment | x *= y |
3 | %= | Assignment | x %= y |
3 | <<= | Assignment | x <<= y |
3 | >>= | Assignment | x >>= y |
3 | >>>= | Assignment | x >>>= y |
3 | &= | Assignment | x &= y |
3 | ^= | Assignment | x ^= y |
3 | |= | Assignment | x |= y |
2 | yield | Pause Function | yield x |
1 | , | Comma | 5 , 6 |
In the above table, bold entries indicate ECMAScript 2015 (ES6) or higher.
<!DOCTYPE html> <html> <body> <p id="tacode"></p> <script> let p = 10 + 4 * 2 / 2 * 4 ^ 7; document.getElementById("tacode").innerHTML = p; </script> </body> </html>
Output:
In the above example, multiplication will be performed first then addition will be done because multiplication has higher precedence.