JavaScript Coding Conventions

Do you guys have a rule against using JavaScript short circuit evaluation?

Basically instead of writing:

var interval = externalData.interval;

if (typeof interval !== ‘undefined’) {

interval = TimeInterval.fromIso8601(interval);


you would do:

var interval = externalData.interval || TimeInterval.fromIso8601(interval);

This is used extensively in the jQuery library, so it has broad browser support.

We generally use typeof x === ‘undefined’ everywhere for two reasons:

  1. The coercion to boolean in a || b uses “truthiness”, so if a is 0, or empty string, or any of the other miscellaneous values that are considered falsy, you can end up using the default value unintentionally. We’ve had bugs in the past caused by this, so rather than worry about it on a case-by-case basis, the typeof check always works the same way.

  2. The typeof check actually ends up being faster than the boolean coercion, surprisingly. Even though the code makes you think it’s going to get the type of x as a string, then do a string comparison with ‘undefined’, it actually doesn’t do any of that. Since even in the wild west of JavaScript, scripts can’t influence how typeof works, or interfere with string literals, or impact reference equality checks, the VM can easily collapse it down to a single instruction.