I've been studying closures lately and beginning to get a hang of it, i understood from contents online and from my former question here that closures are created when a function is created inside another function (Don't know if this is the only condition for closure to exist). I decided to experiment more on this and these set of code got me confused, i didn't expect the output.
var f = [];
for(var i = 0; i < 3; i++){
f[i] = function(){
console.log("Number " + i);
}
};
for(var i = 0; i < 3; i++){
f[i]();
}
//Actual Output
//Number 0
//Number 1
//Number 2
//Expected output
//Number 3
//Number 3
//Number 3
I think i should also mention that when i replaced the second loop with Function.forEach
like this
f.forEach(function(i){
i();
});
it printed the expected output. What am i missing?