Example:
var o = {};
for(var i = 0; i < 5; i++) {
o[i] = function () {
console.log(i);
};
}
o[3]();
When I call o3, it will always display 5 on the console, even if I call o0, o4, or any one of those. It will always display 5 because that’s the last value i had. How do I make it display the value of i when the anonymous function is made? As in o3 should display 3 in the console.
You should do:
What happens is that you create something called closure so as to keep the state of i.
Closure means that an inner function keeps a reference to the outer function and so gains access to its variables and parameters (even after the outer function has returned).
A trivial example for closure is:
A self-executing (self-invoking, or immediate) function is a function that is called right after it is declared.
The combination of both and the fact that only functions have scope in Javascript, leads you to the technique mentioned above to create a scope with a new function which keeps the state of i, which would otherwise be changed by the inner function because of closure.