Does a javascript if statement with multiple conditions test all of them?

Viewed 113226

In javascript, when using an if statement with multiple conditions to test for, does javascript test them all regardless, or will it bail before testing them all if it's already false?

For example:

 a = 1
 b = 2
 c = 1

 if (a==1 && b==1 && c==1)

Will javascript test for all 3 of those conditions or, after seeing that b does not equal 1, and is therefore false, will it exit the statement?

I ask from a performance standpoint. If, for instance, I'm testing 3 complex jQuery selectors I'd rather not have jQuery traverse the DOM 3 times if it's obvious via the first one that it's going to return FALSE. (In which case it'd make more sense to nest 3 if statements).

ADDENDUM: More of a curiosity, what is the proper term for this? I notice that many of you use the term 'short circuit'. Also, do some languages do this and others dont?

10 Answers

The && operator "short-circuits" - that is, if the left condition is false, it doesn't bother evaluating the right one.

Similarly, the || operator short-circuits if the left condition is true.

EDIT: Though, you shouldn't worry about performance until you've benchmarked and determined that it's a problem. Premature micro-optimization is the bane of maintainability.

From a performance standpoint, this is not a micro-optimization.

If we have 3 Boolean variables, a, b, c that is a micro-optimization.

If we call 3 functions that return Boolean variables, each function may take a long time, and not only is it important to know this short circuits, but in what order. For example:

if (takesSeconds() && takesMinutes())

is much better than

if (takesMinutes() && takesSeconds())

if both are equally likely to return false.

That's why you can do in javascript code like

var x = x || 2;

Which would mean that if x is undefined or otherwise 'false' then the default value is 2.

It will only test all the conditions if the first ones are true, test it for yourself:

javascript: alert (false && alert("A") && false);

It short circuits - only a and b will be compared in your example.

It exits after seeing that b does not equal one.

For this case:

a = 1
b = 2
c = 1

if (a==1 && b==1 && c==1)

You can use:

if ([a, b, c].every(x => x == 1))
    // do something if a, b and c are equal to 1.

If you want to know if at least one is equal to 1, use the some() method instead of every():

if ([a, b, c].some(x => x == 1))
    // do something if a, b or c is equal to 1.

every() and some() are array methods.

Related