Guarding in JavaScript

After looking at JavaScript programming sessions by Douglas Crockford (here), I couldn't stop but admire JavaScript. There are many many impressive things in JavaScript but one of the eye-catchy thing was guarding operator in JavaScript. The && operator in JavaScript can be acted in two ways. The normal 'and' operator which is used in determining the conditional logic results. The other lesser known feature of JavaScript is the guard operator. In following code -
/* The if is checking if specs is not undefined, false, null,
"" (empty string) or 0 (numeric zero) as these all values
are falsy conditions in JavaScript */

     width = specs.width;

// To avoid the if condition you can simply do like -

width = specs && specs.width;

/* This makes sure that specs is not falsy and they
returns the second operand which is convenient
way to write null check */

The same is with || operator too. If the first operand is falsy then it just returns the second operand instead. Consider following code:
name = || "Name not set";
/* Use the, but if name doesn't have a value, use default
value instead. */
Very simple and very efficient!

Published April 25 2008

blog comments powered by Disqus