Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
9
rated 0 times [  13] [ 4]  / answers: 1 / hits: 117856  / 15 Years ago, fri, december 18, 2009, 12:00:00

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?


More From » javascript

 Answers
83

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.


[#98039] Tuesday, December 15, 2009, 15 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
reed

Total Points: 725
Total Questions: 85
Total Answers: 89

Location: Singapore
Member since Sat, Jul 25, 2020
4 Years ago
;