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.
Written by Chase Adams
Related protips
Have a fresh tip? Share with Coderwall community!
JavaScript on a page runs with the privileges of that origin. One altered library, tag manager, or snippet can read inputs, change what people see, and call your APIs as the user.
Security insights from Cside