I've been trying to learn some javascript and I ran into a strange scoping problem I was hoping someone here could help with. I have a fair amount of experience with functional programming, but very little with javascript, so please excuse the unidiomatic code.
> I've been trying to learn some javascript and I ran into a strange > scoping problem I was hoping someone here could help with. I have a > fair amount of experience with functional programming, but very little > with javascript, so please excuse the unidiomatic code.
> Now, I'd not expect > functions[0](); > to alert with 0, but instead it alerts with 5. Why is that, and how > can I work around it?
Because i *is* 5 after the loop is finished. All of the functions created are referencing the same i variable. If the for loop is run in the global context, then i is a global variable. If not, i is a local variable and part of a closure formed by assigning references to the functions to the global functions array.
Something like this will produce the desired results: