JavaScript Operator Precedence Tutorial

In this section, we will learn what the Operator Precedence is and how it works in JavaScript.

Note: we’re assuming you’re familiar with JavaScript arithmetic operators.

What is Operator Precedence in JavaScript?

Consider the statement below:

`var res = 10 – 2 * 4 /2`;

What’s the final value of the `res` variable?

The final value is 6. But how we’ve got this value?

This is where precedence comes in.

Based on precedence rules, arithmetic operators have different priority.

For example, the priority of the multiplication `*` operator is higher compared to addition `+` operator and so if we had an expression like `10+5*2` the result will be 20. This means in the previous expression, first the two values 5 and 2 are multiplied together and the result is added to the value 10.

Arithmetic Operators Precedence

In the list below, you can see operators in order of decreasing precedence:

Operators Associativity
() Left to Right
** Right to Left
* / Left to Right
+ – Left to Right
= Right to Left

As the table above shows, parentheses have the highest priority, next is exponentiation and after that we have `multiplication& division` operators and next is `addition& subtraction` operators and at the end we have `assignment` operator with the lowest precedence.

Example: arithmetic operator precedence

For example, if we had an expression like this:

var iVar = (10 + 20) * 10;

First because the parentheses have higher priority than multiplication, the result in the parentheses should be declared first (The result is 30) and then this value 30 is multiplied by 10 and we get 300 and at the end it comes to the assignment operator so this result is assigned to the `iVar` variable.

Associativity of Operators

Associativity declares the order of operand execution.

For example, the associativity in arithmetic operators is from Left to Right. This means if we have an expression like `(4/2)*4`, the left operand executes first and then the right operand. So the result of the mentioned expression is:

2*4 = 8.

As you can see, first, the result of the parentheses on the left side was declared and then this result is multiplied by the operand on the right side.

Example: associativity of operators in JavaScript

let a = 10 ;
let b = 20;
let c = 30 ;
let d = 40;

let result = (a+b) * d; // (10+20) * 40
console.log("The result is: "+ result);

result = ((a+b) /2) * c; // ((10+20)/2) * 30
console.log("The result is: "+ result);

result = c+d/10 * d; // 30+((40/10) * 40)
console.log("The result is: "+ result);

Output:

The result is: 1200

The result is: 450

The result is: 190

Leave a Reply