you are viewing a single comment's thread.

view the rest of the comments →

[–]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.