Follow

Operator Precedence

(Using order of operations in JavaScript)


When writing arithmetic in JavaScript, operator precedence dictates the order in which operations are performed.

(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

For a more complete list, you can checkout this article on w3schools.com:
http://www.w3schools.com/js/js_arithmetic.asp

Have more questions? Submit a request

Comments

Powered by Zendesk