JavaScript - - By James Edwards

Assignment inside a Condition

It’s very common in PHP to see code written like this:

if($summary = get_post_summary())
{
    return $summary;
}

What I’m referring to is assignment inside a condition. Cunningly enough, it can be done in JavaScript too, although it’s far less common:

if(summary = document.getElementById("post-summary"))
{
    return summary.innerHTML;
}

At first glance you’d be forgiven for thinking that’s a typo! Indeed, some debuggers will flag that with a warning, asking if you meant a test for equality (==) and mistyped it as assignment (=).

But it’s not a mistake—the key to understanding it is to understand two things:

First, assignment returns a value (the value you assigned). Second and most importantly, the value it returns evaluates to true or false, and ultimately determines whether the condition passes.

Now, in the world of DOM evaluation and traversal, this technique is a safe and predictable one because DOM nodes either exist or they’re null—and null is required to evaluate to false. So in the code example above, the condition will evaluate to true if the "#post-summary" element exists, or false if it doesn’t.

Equally, you can use the same trick to iterate up an unknown hierarchy, traversing through successive parents using while(). This example builds an array of every node name between an event target and the #document:

var names = [], node = e ? e.target : event.srcElement;
do
{
    names.push(node.nodeName);
}
while(node = node.parentNode)

But elsewhere in JavaScript, you could find yourself in much less reliable territory, because how true or how false many values turn out to be is not at all intuitive.

Both positive and negative numbers, for example, evaluate to true except zero and NaN. And bizarrely, an object created with the Boolean constructor always evaluates to true, even if it was created as new Boolean(false)!

So be warned! Syntax like this is not for the fainthearted; nor should it be used in a cavalier way, with overreliance on type conversion and the casting of arbitrary values. But used well in suitable circumstances, it can simplify many conditions to produce faster and leaner code.

Thumbnail credit: sbwoodside

Sponsors
Login or Create Account to Comment
Login Create Account