Question

Update: rewriting question because original question had false assumptions (I was running code in a console that had already initialized the variables I thought were undefined).

This makes sense:

var obj = { 'whichScope': a };
obj.whichScope; //"ReferenceError: a is not defined"

But then how come this next example doesn't throw an error? And if the second line is getting run before the first line, why doesn't obj.whichScope resolve to "After"?

var obj = { 'whichScope': a };
var a = "After";
obj.whichScope; //"undefined"

If "var a" in the previous example runs before obj is initialized, does any part of 'a = "After";' also run before obj is initialized?

var a = "Before";
var obj = { 'whichScope': a };
a = "After";
obj.whichScope; //"Before"

If whichScope refers to a function that returns 'a' then it does resolve to "After" in the last example.

Was it helpful?

Solution

That is called variable hoisting.

References:

Variables (declared with var) and functions are hoisted to the top of their scope.

So technically, your script is like this:

var a;  // = undefined
var obj = { 'whichScope': a };
a = "After";

Although your first example doesn't do what you say. The value of obj.whichScope is undefined, as expected.

DEMO: http://jsfiddle.net/pRQwK/

As for your last statement, If whichScope refers to a function that returns 'a' then it does resolve to "After" in the second example. - that is because the value of a isn't captured (by a closure). When setting a property, its value is captured immediately (unrelated to a closure).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top