1

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?

  • possible duplicate of [Why JavaScript functions always return a value?](http://stackoverflow.com/questions/20915450/why-javascript-functions-always-return-a-value) – Ayman Safadi Apr 13 '14 at 04:24

3 Answers3

1

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.

Community
  • 1
  • 1
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
1

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

Aaron
  • 705
  • 10
  • 19
0

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;
Suman Bogati
  • 6,289
  • 1
  • 23
  • 34