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
  • 56,466
  • 29
  • 168
  • 265
Richard
  • 4,809
  • 3
  • 27
  • 46

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
  • 106,495
  • 44
  • 176
  • 212