C B
C B

Reputation: 13314

Shorter way to check for undefined in JS

Looking for a better idiom to use..

var x = module;  // Reference Error
var x = typeof module==='undefined' ? window : module;

is there a shorter way to check for the existence of module?

Upvotes: 0

Views: 1734

Answers (2)

ThiagoPXP
ThiagoPXP

Reputation: 5462

I like to use double bang (!!) for that.

The first bang casts the variable to a Boolean, and the second undoes the logical that was performed by the first bang.

var x = !!module ? module : window;

This is also a shorter way to verify for null and undefined at the same time. This might be what you want.

Examples:

var foo = 1;
console.log(!!foo); //true

var bar = { name: "test" };
console.log(!!bar); //true

var module = null;
console.log(!!module); //false

var module = undefined;
console.log(!!module); //false

Upvotes: -1

Krease
Krease

Reputation: 16215

var x = module;  // Reference Error

Technically you're not checking for undefined - ie: if module===undefined (which many of the other answers are assuming) - you want to know whether the module is declared.

In that case, your second example is the way to do it:

var x = typeof module==='undefined' ? window : module;
// replace window with whatever you want your fallback value to be

Upvotes: 5

Related Questions