Because JavaScript does not have block scope, it has function scope. There is only one i
variable, and it exists for the whole function. It is changed from 0, to 1, and so on, up to 5. All of the closures reference this same variable.
You can fix it by passing the value in to an immediately-invoked function that returns another function:
result.push((function (i) { return function() { return i; } }(i));
In this case you pass the value of i
in to the outer function, which returns another function that returns the argument to this inner function, effectively capturing the value of the outer i
at that particular moment.