Friday, 15 June 2012

&& / || operator strangeness in JavaScript -



&& / || operator strangeness in JavaScript -

so, working on project of mine, when came across problem this:

var 1 = 1; var 2 = 2; var 3 = 7; if (one === 1 || 2 === 2 && 3 === 3) { console.log("ok"); // prints out ok }

i'm pretty confused since don't think should print out "ok". thought since status after && operator false, shouldn't run, i'm evidently wrong. can clarify why it's working?

in javascript, operators not evaluated left-to-right, operators have more precedence others. higher precedence (in case, && operator of precedence 13) evaluated before others (||, precedence 14).

for particular case, need grouping conditionals in order accomplish functionality want:

if ((one === 1 || 2 === 2) && 3 === 3) { console.log("ok"); // prints out ok }

jsfiddle

javascript

No comments:

Post a Comment