JavaScript the property of an object returns indefinite, why?

advertisements

I am studying JS and was wondering why any not defined JS Object property returned undefined.

window.myVar // undefined

and now If I try to access the global property myVar (which is kind of the same as window.myVar) JS will throw an error:

myVar // error: myVar is not defined

notice that initializing variable with

var myVar; // undefined

so, could someone please explain what is the process behind this?


I am studying JS and was wondering why any not defined JS Object property returned undefined.

Because the specification says so:

  1. Let desc be the result of calling the [[GetProperty]] internal method of O with property name P.

  2. If desc is undefined, return undefined.

While global variables become properties of the global object, trying to resolve a variable and trying to access a property of an object are two different things.

If you are trying to access a variable that is not defined, a reference error is thrown:

  1. If Type(V) is not Reference, return V.

  2. Let base be the result of calling GetBase(V).

  3. If IsUnresolvableReference(V), throw a ReferenceError exception.


There is not really much else to say about it. It is this way because the language is defined this way. If you are asking what's the reasoning behind this, then you have to ask someone who actually works on the language specification.