JS - Logical AND Operator Used as If Statement?

James

Well-known member
Reading an article on NetTuts+ by Jeffrey Way made me intrigued by the concept of this. I haven't ran any testing to check if an if() statement or this method runs faster... but it's interesting nonetheless.

For users who don't want to read the article, Jeffrey basically states that with JS when using the AND operator, the second statement only runs if the first statement is true.
So:
Code:
var a=5;
b=10;
if((a===5) && (b===10)){
alert('yay');
}
b===10 will only run if a=5. With this in mind, other methods become available to us, such as:
Code:
!document.getElementById('contents') && createElem('div', 'contents', 'hello world');
This will check if an element exists with an ID of contents. If it doesn't, it will create a DIV with an ID of contents.

A more real-life example was also given:
Code:
!window.jQuery && document.write('<script src="localjQuery.js"><\/script>');
which downloads a local copy of jQuery if the copy was not retrievable from the CDN for whatever reason.


I found it an interesting read and decided to share it :p
 
/slightly OT

[...] with JS when using the AND operator, the second statement only runs if the first statement is true.
It's true for C, C++, Java and PHP as well.
(can't say about other languages, I'm only familiar with these 4).

This is the short-circuit evaluation of expressions. ie, the evaluation of a logical expression stops when you have sufficient information to decide the outcome of the whole expression. Thus when using logical OR, if the first sub-expression evaluates to true the second sub-expression is not evaluated because no matter what it evaluates to, the result will always be true.

Similarly in a logical AND, if the first sub-expression evaluates to false, the result will be false no matter what the other sub-expressions evaluate to. :)
 
Thanks for the explanation Shadab :P
Do you know if this method is faster than a standard if() statement? I must remember to run some testing at some point.
 
Do you know if this method is faster than a standard if() statement?
I'm not a Javascript guy, so I don't know and I'm unable to write tests to benchmark it in JS. :(

But in PHP, yes it's slightly faster. We're looking at an improvement of just about 2000 ms over 10,000,000 iterations; which is 0.2 x 10^-6 second per iteration. That's micro optimization and obviously not something we should go crazy about.

In the conclusion section of the article over at NetTuts+ they say "It certainly makes for slightly less readable code", and rightly so!

I think you'll find this is common knowledge ;)
What may be obvious or common knowledge for some of us, may not be so for others who are less technical. :)
 
Top Bottom