NullPointerException
NullPointerException

Reputation: 491

JavaScript any object's property returns undefined, why?

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

Answers (3)

Felix Kling
Felix Kling

Reputation: 816930

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.

Upvotes: 1

Aaron
Aaron

Reputation: 767

Felix is correct, this may help clarify things: Understanding undefined and preventing reference errors

Upvotes: 1

Suman Bogati
Suman Bogati

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

Related Questions