0

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?

C B
  • 12,482
  • 5
  • 36
  • 48

2 Answers2

5
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
Krease
  • 15,805
  • 8
  • 54
  • 86
-1

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
ThiagoPXP
  • 5,362
  • 3
  • 31
  • 44
  • The problem with that, is that this checks for truthyness and not trueness. !!0 is still false. – Győri Sándor Apr 12 '19 at 11:54
  • 1
    The question states they want to check for a complex object existence "module", not for numbers. If you know no numbers or ZERO should be the variable value, double bang is perfect fine. In cases ZERO can be a value, you could check for zero as well. `!!module && module !== 0` – ThiagoPXP Apr 15 '19 at 20:31