Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can someone explain me why "operator precedence" applies to logical operators like "||", "&&" in javaScript

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.

like image 651
user13104441 Avatar asked Dec 18 '25 19:12

user13104441


1 Answers

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)

like image 117
Mingwei Samuel Avatar answered Dec 20 '25 09:12

Mingwei Samuel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!