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:
inneris declared as a property on the global object and the value is set toundefinedouteris invoked.- An execution context is created for
outerwhose scope chain includesouterVarand the global object. - The value of the
innerproperty on the global object is assigned a reference to the function definition. - The execution context for
outerfinishes. (the related scopes are removed? marked for GC?) inneris invoked.- An execution context is created whose scope chain includes
innerVarand the global object. outerVaris not found in scope
Can someone please explain why outerVar is defined?