Search code examples
javascriptoperator-precedence

Why is "and" evaluated before "equal"


In Javascript precedence of strict equal (10) is greater than logical and (6) then how does this code works

var a;
console.log("value of a is", a);
if (a && a.test === "test") {}

Should it not throw error

cannot read test of undefined.

And to add salt to the wound precedence of member access is higher than both of them (19).

What am i missing?


Solution

  • Some programming languages, like JavaScript, evaluate logical expressions lazily. This means that if the first part of your expression (a) is false, the interpreter sees no reason for even executing the second part (a.test === "test") and thus no error is thrown.

    To clarify, precedence does not define the actual order in which an expression is executed, only the effective order. So that the member access operator hast highest precedence does not mean it will be executed first. The interpreter can still evaluate a first, without affecting the outcome of any of the higher precedence operators. You can think of precedence as implicit brackets, if you write the expression as (a) && ((a.test) === "test") you can clearly see that a can and will be evaluated first, as it is at the very left of expression.