Curiosities about using closures in loops in Javascript

Just execute this code in your browser and find the ten differences between the two loops:

  1. <html>
  2. <body>
  3. <script type="application/javascript;version=1.7">
  4.  
  5. let funs = {};
  6. let msg = "";
  7.  
  8. for (let i = 0; i < 10; i++) {
  9.   funs[i] = function() {
  10.     msg += "i = " + i + "n";
  11.   }
  12. }
  13.  
  14. for (let i = 0; i < 10; i++) funs[i]();
  15.  
  16. alert("Without redeclaration: n"+msg);
  17.  
  18. msg = "";
  19. for (let i = 0; i < 10; i++) {
  20.   let idx = i;
  21.   funs[i] = function() {
  22.     msg += "i = " + idx + "n";
  23.   }
  24. }
  25.  
  26. for (let i = 0; i < 10; i++) funs[i]();
  27.  
  28. alert("With redeclaration: n"+msg);
  29.  
  30. </script>
  31. </body>
  32. </html>

As you can see, the i variable works as if it was declared outside the loop, so it’s reused inside it. Thus, if you use it inside a closure, all the closures share the same reference and can see the changes produced during the iterations.

However, in the second loop a new fresh local variable is defined for each iterations, so the values aren’t shared among the closures.