Just execute this code in your browser and find the ten differences between the two loops:
-
<html>
-
<body>
-
<script type="application/javascript;version=1.7">
-
-
let funs = {};
-
let msg = "";
-
-
for (let i = 0; i < 10; i++) {
-
funs[i] = function() {
-
msg += "i = " + i + "n";
-
}
-
}
-
-
for (let i = 0; i < 10; i++) funs[i]();
-
-
alert("Without redeclaration: n"+msg);
-
-
msg = "";
-
for (let i = 0; i < 10; i++) {
-
let idx = i;
-
funs[i] = function() {
-
msg += "i = " + idx + "n";
-
}
-
}
-
-
for (let i = 0; i < 10; i++) funs[i]();
-
-
alert("With redeclaration: n"+msg);
-
-
</script>
-
</body>
-
</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.