JS Optimisation #2 – Assignment/Test Combo

, ,

This tip considers a cheeky shorthand to assign and test simultaneously within an if statement.

Okay, so this one’s controversial. Take this code:

if (myVar = document.getElementById("myNode")) {
    alert(myVar.id);
}

You’d be forgiven for thinking there was a typo (= instead of ==), and rightly so. But this is actually a cheeky shorthand for assigning a value and testing it at the same time.

myVar is first set to whatever the result of document.getElementById("myNode") is, then if a node is found and successfully returned, the test condition will evaluate to truthy and the alert function called.

So what’s the benefit? Well it’s arguable how much of a benefit there is for the amount of confusion you’ll cause, but basically it avoids the need for a separate variable assignment statement:

myVar = document.getElementById("myNode");
if (myVar) {
    alert(myVar.id);
}

Many developers would say it’s a bad idea, it’s hard to debug and will just create more harm than good. Any tip that looks like a typo is bound to cause controversy, but as long as you’re careful how and when you use it and you make other developers aware of this method, I think it’s a handy shortcut and something you shouldn’t be scared of.

As an aside, I had a thought: How about combining this method with the mini if statement:

(myVar = document.getElementById("aNode")) && alert(myVar.id);

If it wasn’t controversial before, it is now!