Last Updated: February 25, 2016
·
1.691K
· realchaseadams

The Pitfall of Using || As A Fallback in Javascript

Recently I was going through some javascript with a co-worker and we found the equivalent of this:

var baz = foo || bar;

Where baz was to be set to bar if foo didn't exist.

This seems to be a common misconception of an acceptable fallback, for a variable being undefined, but will cause the javascript engine to scream at you that "foo is not defined" and fail.

The right way to do this is to check that foo or bar are undefined:

var baz;

if (typeof foo !== 'undefined') {
  baz = foo;
} else if (bar !== 'undefined') {
  baz = bar;
} else {
  baz = null;
}

Save future developers working on your code frustration and be cautious by not assuming existence of variables, and checking for them first.