3

Why on earth does this work:

FOO = window.FOO || {isFoo: true};

But this doesn't:

FOO = FOO || {isFoo: true};

Since FOO and window.FOO both reference the same thing (both are running in the global scope).

Ali
  • 54,239
  • 29
  • 159
  • 255
Richard
  • 4,650
  • 3
  • 25
  • 45

1 Answers1

4

Because FOO is not declared, but window is. Trying to access an undeclared variable will throw a ReferenceError, but accessing an undefined property will not.

You can get around it by using typeof:

FOO = typeof FOO != 'undefined' ? FOO : {isFoo: true};
David Hellsing
  • 102,045
  • 43
  • 170
  • 208