Operator precedence (JavaScript)

Prev Next

Order of operations in JavaScript


When writing arithmetic in JavaScript, operator precedence dictates the order in which operations are performed. For example, multiplication has a higher precedence than addition. This means that if an expression contains both multiplication and addition operators (such as the example below), the multiplication will be evaluated first.

(Example) 

var x = 10 + 5 * 2;

In the above example, what is the value of x?
Luckily, JavaScript uses the same operational order as traditional mathematics, which tells us that x = 20.

(Example)

var x = (10 + 5) * 2;

When using parentheses, the operations inside are calculated first. In the above example, x = 30.

(Example)

var x = 10 + 5 - 2;

When operations have the same precedence (like addition and subtraction), they are calculated from left to right:
In the above example, x = 13.


Here is a basic list of operator precedence in JavaScript

Order

Operator

Description

Example

1

( )

Expression grouping

(10 + 5)

2

*

Multiplication

10 * 5

2

/

Division

10 / 5

2

**

Exponentiation

10 ** 5

3

+

Addition

10+5

3

-

Subtraction

10-5