I am going through book "Java Script Ninja" and there is chapter on closures and scope.
There is code example:
var innerHolder;
function outerFunction() {
console.log("outerFunction: "+x);
function innerFunction() {
console.log("innerFunction: "+x);
}
innerHolder = innerFunction;
}
console.log("outerScope "+x);
var x = 15
outerFunction();
innerHolder();
Result of this is:
outerScope undefined
outerFunction: 15
innerFunction: 15
Then the book says:
All variables in an outer scope, even those declared after the function declaration, are included.
Within the same scope, variables not yet defined cannot be forward-referenced.
I do understand the second point, but the first point is not entirely clear to me. It appears as this is true but only if the variable is actually declared before function call is made. In my logic because variables are not hoisted if variable is declared after call to inner function, it is not in the outer scope at the time and therefore it will not be picked by closure. Is that correct?
I.e. If I modify the code:
console.log("outerScope "+x);
outerFunction();
innerHolder();
var x = 15
The result will be:
outerScope undefined
outerFunction: undefined
innerFunction: undefined