The closure rule is: functions are executed using the scope chain that was in effect when they are defined.
In the setTimeout callback function below, x is not yet in scope at the time of definition. Therefore, the program should print undefined, but it prints 7, why? what am I missing?
var foo = function () {
setTimeout(function (){
console.log(x);
}, 3000);
};
var x = 7;
foo();
Or, is it because the above code is exactly same as the below?
var x = 7;
var foo = function () {
setTimeout(function (){
console.log(x);
}, 3000);
};
foo();