Set a variable if undefined in JavaScript

Yes, it can do that, but strictly speaking that will assign the default value if the retrieved value is falsey, as opposed to truly undefined. It would therefore not only match undefined but also null, false, 0, NaN, "" (but not "0").

If you want to set to default only if the variable is strictly undefined then the safest way is to write:

var x = (typeof x === 'undefined') ? your_default_value : x;

On newer browsers it’s actually safe to write:

var x = (x === undefined) ? your_default_value : x;

but be aware that it is possible to subvert this on older browsers where it was permitted to declare a variable named undefined that has a defined value, causing the test to fail.

Leave a Comment