Can someone explain me why operator precedence applies to logical operators like || and && in JavaScript? What does that mean in an operation like:
true || false && false
the false && false is evaluated first because the && operator is having a higher precedence than the || operator in JavaScript. according to how I know the false && false is not evaluated by the JavaScript engine because before the || operator there is a true literal and when something is true before the || operator the thing after the || operator will not be evaluated this is called "short-circuiting of logical operators" in JavaScript another example will be:
true || alert()
the function call never takes place even though the function call is having higher precedence than the || operator and another example is
true || x = 7
if short-circuiting of logical operators is true in JavaScript then the above code must not give an error because the x = 7 is not evaluated, since before the || operator there is a true literal.
Operator precedence just determines grouping, not actual evaluation order: https://stackoverflow.com/a/46506130
true || false && false becomes true || (false && false) but is still evaluated from left to right.
true || alert() is evaluated as true || (alert()) and NOT (true || alert)()
true || x = 7 is evaluated as (true || x) = 7 and causes an error, NOT true || (x = 7)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With