Question

Just a simple question :)

if I have :

var user = {'name': 'Fred'};

So

console.log(user.name); // Fred
console.log(user.age); // undefined

But

console.log(test); // ReferenceError: test is not defined

I don't understand why because for me it's the same as

console.log(window.test); // undefined

In my project, i try to check if a global variable exist but I have a referenceError... I don't really understand why the followinf code doesn't work...

if (TestGlobal) // ReferenceError: TestGlobal is not defined
   console.log(' allo 1 ');

if (typeof(TestGlobal ) !== 'undefined') // Ok
   console.log(' allo 1 ');
Was it helpful?

Solution

…and a simple answer:

  • Property references always evaluate to their value or the undefined value if the key does not exist, as long as the base value is not undefined (then a TypeError would be thrown).
  • Variables throw ReferenceErrors if not defined before, unless they are used with the typeof keyword (where they just evaluate to "undefined").
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top