Short Circuit and the Javascript IF Statement

A quick javascript tip that lets you eliminate small IF statements

Ok so it’s not really that kind of Short Circuit, though it is almost as cool. In javascript, as in many programming languages logical and statements short circuit if the first element isn't true. So basically if you say

if(false && true)

Javascript start processing the expression sees the false, knows that the statement can never be true and moves on without ever touching the true. This has some interesting practical applications. Because it means that you can use the first statement as an IF and the second can be your command to be executed.

Pull up your javascript console and try this:

( 1 === 1 ) && alert('Johnny 5 is alive!');
yep amazing! It does the same thing as:

if( 1===1) {
      alert(' Johnny 5 is alive!');
}

Sure there are other short forms of that if statement that would work. But, the short circuited form is clever, and interesting. It really shows off one of the interesting aspects of the language that you don’t run into everyday. I think it’s kind of elegant. Not as readable, sure. Still a neat trick for creating slightly more compact code. I wish I could take credit for it, but I found it reading through someones pull request on git hub. When I find the project again I’ll post a link to it... Now it’s time for some hot chocolate and breakfast.

If you enjoyed this article please share it! Also, I have a newsletter that you might enjoy as well. Thanks! -Daniel

Published: 28 Jan 2012 | Tags: tip , programming , javascript