Home > Software engineering >  Operator precedence for logical AND (&& )and logical OR (||)
Operator precedence for logical AND (&& )and logical OR (||)

Time:04-24

As per the operator precedence table for JavaScript, I can see that && has higher precedence than ||.

So, for the following code snippet:

let x, y;
let z = 5 || (x = false) && (y = true);
console.log(z);  // 5
console.log(x);  // undefined 
console.log(y);  // undefined 

I thought that && should be evaluated first and after short-circuiting for the && part, x would be assigned the value false. And then only, || would be tried to be evaluated.

But, from the output of the console.log, I can clearly see that's not the case here.

Can someone please help me what am I missing here?

Thanks in advance.

CodePudding user response:

What the operator precedence of && of || means is that this:

let z = 5 || (x = false) && (y = true);

gets evaluated as:

let z = 5 || ((x = false) && (y = true));

and not as

let z = (5 || (x = false)) && (y = true);

It's not something that indicates when the values on each side of an operator is evaluated. That's done by the mechanics of each individual operator. For example, for ||, it's specified here:

1. Let lref be the result of evaluating LogicalANDExpression.
2. Let lval be ? GetValue(lref).
3. Let lbool be ToBoolean(lval).
4. If lbool is false, return lval.
5. Let rref be the result of evaluating BitwiseORExpression.
6. Return ? GetValue(rref).

It evaluates GetValue(lref) before GetValue(rref) runs.

In other words, operator precedence indicates which tokens are applied to which operator, and in what order, but not how/when a given operator evaluates the values on its left and right side.

  • Related