Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Operator precedence for logical AND (&& )and logical OR (||)

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading