Bimal Dason Stack Overflow • Recommends
On “How to ensure closures created in a loop capture the value of the loop variable from their particular iteration?”
We will check , what actually happens when you declare var and let
one by one.
Case1 : using var
<script>
var funcs = [];
for (var i = 0; i < 3; i++) {
funcsi = function () {
debugger;
console.log("My value: " + i);
};
}
console.log(funcs);
</script>
Now open your chrome console window by pressing F12 and refresh the page.
Expend every 3 functions inside the array.You will see an property called [Scopes] .Expand that one. You will see one
array object called "Global" ,expand that one. You will find a property 'i' declared into the object which having value 3.
Conclusion:
When you declare a variable using 'var' outside a function ,it becomes global variable(you can ch…