user3552105
user3552105

Reputation: 109

JS Logical And / Or

Can someone explain to me why both of these alert 'True'? The logical OR makes sense I think - The OR short circuits after the first test: 100 != 90, therefor it is true. By why does the AND short circuit after the first test and not keep going?

if (100 != 90 && 100 && 190 && 200 && 290){
    alert("true");
} else {
    alert("false");
}

if (100 != 90 || 100 || 190 || 200 || 290){
    alert("true");
} else {
    alert("false");
}

EDIT: THANK YOU EVERYONE FOR YOUR HELP! BASED ON YOUR SUGGESTIONS, I THINK I WILL AMMEND MY CODE TO THIS:

var trains = [90,100,190,200,290];
var testValue = 100;

if (trains.indexOf(testValue) >= 0){
    alert("true");
}

Upvotes: 0

Views: 63

Answers (2)

Matt Burland
Matt Burland

Reputation: 45135

This will evaluate to true:

if (100 != 90 && 100 && 190 && 200 && 290)

Because each part is truthy. Any non-zero value in javascript is consider to be equivalent to true. So you have:

if (true && true && true && true && true)

Which is, obviously, true. It's not short circuiting, because none of the values are false.

I suspect the mistake you've made is to think that this:

if (100 != 90 && 100)

Is doing the same thing as this:

if (100 != 90 && 100 != 100)

Which is simply not how the syntax works. It's easy to say in words "if 100 doesn't equal 90 and doesn't equal 100" and understand what that means, but in javascript (and most other languages) you have to be explicit.

Now obviously this gets really tedious if you have a value that you need to compare with a long list of values, for example:

if (x != 90 && x != 100 && x != 190...)

And in a case like that, it's usually easier to put all your values into an array and instead ask if x is contained (or not) in that array:

var values = [90,100,190,...]

if (!values.some(function(e) { return e === x; })) {
    // the value x is not in the array values
}

Upvotes: 1

Chris Wissmach
Chris Wissmach

Reputation: 505

For the &&, the first 100 != 90 evaluates to true. Then, the integers are implicitly converted to bools, where 0 = false, true otherwise. The true will carry through the numbers, of which none are 0.

Your comment about || is correct.

Upvotes: 0

Related Questions