I am following along with an article on javascript closures.
In trying to learn the particulars of execution context, I came across a result that surprised me.
var globalVar = 'g';
var inner;
var outer = function() {
var outerVar = 'o';
inner = function() {
var innerVar = 'i';
console.log(innerVar, outerVar, globalVar);
}
}
outer()
inner() // Q: What does this log out?
This actually outputs i o g
.
I expected to see i undefined g
.
Here is my understanding of the process. I would like to understand my error:
inner
is declared as a property on the global object and the value is set toundefined
outer
is invoked.- An execution context is created for
outer
whose scope chain includesouterVar
and the global object. - The value of the
inner
property on the global object is assigned a reference to the function definition. - The execution context for
outer
finishes. (the related scopes are removed? marked for GC?) inner
is invoked.- An execution context is created whose scope chain includes
innerVar
and the global object. outerVar
is not found in scope
Can someone please explain why outerVar
is defined?