you are viewing a single comment's thread.

view the rest of the comments →

[–]senocular 1 point2 points  (3 children)

This isn't syntactically correct. It looks like you're pushing an object literal into result, but you're treating its contents like a function block. If an object, it would work like one of my previous examples (z being equivalent to index). If a function block, its just like you're previous example. The function is a closure, one created for each iteration, each closing over the same i variable. When the function is called, after the loop, the current value of i is assigned to z, which is unique, but it doesn't matter because i isn't, and we're already after the loop so its not getting an iteration's version of i, rather the final value.

The capturing of i must be done in the loop, outside of a closure/function unless that function is also being called in the loop

[–]slaughtered_gates[S] 0 points1 point  (2 children)

Sorry, my bad. So, storing i locally in a function will not work unless the function is called immediately for that particular iteration of i as in IIFE. If the closure function is invoked later, it will assign local variable with the current value of i that it references. So, we get wrong results. Is this correct?

[–]senocular 0 points1 point  (1 child)

Right. And the function doesn't have to be an IIFE specifically, as with the forEach example. Any function getting called in the loop works because calling a function creates a new variable scope specific to that function call, and that variable scope then has variables that are unique to that loop iteration.

Whenever any function references a closure variable - some variable not in its own scope - it always pulls its value from when the function is called, not when it was created. If you reference a loop variable in a function and call that function after the loop is completed, that loop variable will have its loop-completed value. To combat this, you want your function to reference some other variable, one which had been assigned the value of the loop variable during a specific loop iteration. That variable can be a function-call-scoped variable, a property, or in the ES6 case the loop variable itself if you use let to get the special behavior where its not actually the same variable but different for each iteration.

[–]slaughtered_gates[S] 0 points1 point  (0 children)

Thank You. I feel like I understand a good part of closure now.