tags:

views:

235

answers:

6

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, so dome languages do this and others not?

+10  A: 

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.

Anon.
Excellent answer (both the technical part and the management issue). thanks!
DA
Zoidberg
This condition isn't necessarily always about performance. Sometimes you might be doing a null check and say if your null check is condition a and then you try to do a (b == value + 1) for your second check you will get an error if all three conditions if conditions were checked.
infocyde
Indeed, short-circuiting isn't about performance. The original question, however, was asking from a performance standpoint.
Anon.
+1  A: 

It exits after seeing that b does not equal one.

Annie
+1  A: 

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

David M
+4  A: 

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

javascript: alert (false && alert("A") && false);
AlbertEin
+2  A: 

Thats why you can do in javascript code like

var x = x || 2;

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

azazul
+1  A: 

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.

Brad