Reputation: 491
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?
Upvotes: 1
Views: 164
Reputation: 816930
I am studying JS and was wondering why any not defined JS Object property returned undefined.
Because the specification says so:
Let desc be the result of calling the
[[GetProperty]]
internal method of O with property name P.If desc is
undefined
, returnundefined
.
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:
If Type(V) is not Reference, return V.
Let base be the result of calling GetBase(V).
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.
Upvotes: 1
Reputation: 767
Felix is correct, this may help clarify things: Understanding undefined and preventing reference errors
Upvotes: 1
Reputation: 6349
According to variable by mdn
A variable declared using the var statement with no initial value
specified has the value undefined.
So undefined
value for
myVar
var myVar;
Upvotes: 0