It’s very common in PHP to see code written like this:
if($summary = get_post_summary())
if(summary = document.getElementById("post-summary"))
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 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
var names = , node = e ? e.target : event.srcElement;
while(node = node.parentNode)
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
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