Reputation: 2008
So, I was working on a project of mine, when I came across a problem like this:
var one = 1;
var two = 2;
var three = 7;
if (one === 1 || two === 2 && three === 3) {
console.log("ok"); // prints out ok
}
I'm pretty confused with this since I don't think it should print out "ok". I thought that since the condition after the && operator was false, it shouldn't run, but I'm evidently wrong. Can anyone clarify why it's working?
Upvotes: 1
Views: 73
Reputation: 44699
In Javascript, operators are not just evaluated left-to-right, certain operators have more precedence than others. Those with higher precedence (in this case, the &&
operator of precedence 13) will be evaluated before others (||
, precedence 14).
For your particular case, you need to group your conditionals in order to achieve the functionality you want:
if ((one === 1 || two === 2) && three === 3) {
console.log("ok"); // prints out ok
}
Upvotes: 3