Tuesday 1 July 2014

Conditional evaluation in JavaScript - smarter better code

I have been trying to write some very concise code recently, that has a lot of conditional checks build into it. The problem with this, is the whole thing just becomes a long set of IF/ELSE statements, which is horrible to read.

Then I had a brainwave... JavaScript allows for the conditional evaluation of any expression.

so instead of writing this:

if(myCondition==true){
    doOtherFunction();
}

I can write this

    myCondition && doOtherFunction();


or even this

myCondition && myCondition>100 && doOtherFunction();


In fact, I can chain any number of expressions together, as long as they all evaluate to true.
and, it can even include assignment, as assignment is simply an expression.

myCondition && (myOtherVar=999);

And just to put the icing on the cake, I can combine this with Cast-to-Boolean.

Boolean(myCondition) && doOtherFunction();

or

!!myCondition && doOtherFunction();


Ok, the last example is getting a little extreme, but if you are looking for concise code...



No comments:

Post a Comment