Javascript: Exploring a few idioms – Mr. Joel Kemp

In this post, I’ll talk about some shortcut idioms that are used often, basic at their core, and fairly interesting.

Have your own JS idioms that you want to share? I started a collaborative repo on github:

Branching with Inline assignment

if (foo = doSomething()) {}

The quick explanation of how this works is that the function call doSomething() executes and its return value gets stored in foo. The value of foo is then evaluated for truthiness. This is really just a more concise way of saying:

foo = doSomething();if (foo) {}

I don’t particularly like the sacrifice in readability as this idiom still looks out of place to me after all these years.

Exploiting Boolean Operators for Function Execution

callback && callback();

I like this one quite a bit. I often have cases where I’m like:

if (callback) { callback();}

You can one-line it to be more concise:

if (callback) callback();

But that still makes me hate myself.

The expression-based defaulting technique is a quite clever use of the short-circuiting nature of boolean operators.


callback && callback();

If callback doesn’t exist, then the condition is immediately false (since boolean and/&& expects both clauses to be true – hence, the first clause must be true to bother evaluating the second one) and moves on without evaluating the second clause.

If callbackdoes exist, however, then the second clause is evaluated – executing the callback function. Pretty cool.

Expression-based Variable Defaulting

foo || (foo = {});

Similar to the previous idiom, this one also takes advantage of short circuiting.

If foo doesn’t exist (or is some falsy value), then the second clause assigns the empty object to foo

It’s really another way of saying:

foo = foo || {};

which are shorter ways of saying:

if (! foo) {  foo = {};}

Appending an array element using its length

var a = [];a[a.length] = 'foo';

This works because a.length evaluates to 0 initially (empty array) and so ‘foo’ gets stored/appended in a[0]. Another iteration of this idea could be:

var a = [];a[a.length] = 'foo';a[a.length] = 'boo';

After the first assignment, a.length evaluates to 1, so ‘boo’ gets stored/appended in a[1].

This is cute, but it’s more favorable to just use the native push method of arrays.

var a = [];a.push('foo');

Not only would the push version likely yield performance benefits (since it’s a native-code backed function) if used in an intensive loop, but it’s also more readable.