JS Optimisation #3 – If Statement

, ,

This tip points out a shorthand way of implementing a simple if statement.

Sometimes all you want is a simple “if this, then do that” one-liner statement, but you end up using three lines of code when really it can be a lot more straightforward.

The ternary if else statement is a great shorthand for writing a simple if else on one line without it confusing other developers who read your code. But what if you don’t want the else part?

I recently came across a super quick way of implementing a basic if statement. Take the standard:

if (myVal) {
    myFunction();
}

If myVal is truthy, call myFunction. Yep, fine. But how about this?

myVal && myFunction();

By using the logic operator && (AND), you effectively achieve the same result in less code.

The way it works is very simple: When computing a logical expression, whatever is to the right of the operator is only executed if the condition to the left equates to true, effectively behaving as an if. Nice.

You can take this further and add a series of different conditions/expressions in much the same way you would with a normal if statement:

myVal && (myVal2 || myVal3) myFunction();

…and so on.

Go on, use it. You know you want to.

  • Russ

    I never thought of that, great tip!

    However I feel you do need to consider the advantages of reducing code against the disadvantages of readability.

    • http://arraybend.com Ryan Beard

       I take your point. However, I feel the readability of code is more a case of familiarisation. If you do or see something enough it becomes readable by the sheer fact that it’s familiar.