Let vs var differences with for

var funcs = ;

// let’s create 3 functions

for (let i = 0; i < 3; i++) {

// and store them in funcs

funcs[i] = function() {

// each should log its value.

return "My value: " + i;



for (var j = 0; j < 3; j++) {

// and now let’s run each one to see


I have this piece of code. I know that this will print all values and not only 3 like with var. Each of the func[j] has the value "function(){// each should log its value. return"My value: “+i;}”. Why when you run func[0] it knows what it should be printed when you do return "My value: " + i;? I understand that var will keep the value after exiting the loop (3) and will print it each time, but how does javascript knows what i to print when using let? I mean what happens when you actually call func[0]? I understand that we create a scope for each i, but how does actually knows when you call func[0] to actually use that scope for i =0 in order to return correct value?

The reason is because each time through the loop, i gets a new scope thanks to the let or const. In the var version, each closure in the loop captures the same binding, whereas using let/const gives each closure its own unique binding to capture.

Good question BTW. I’ve seen a lot of bugs crop up from defining closures in loops because of how capture semantics work. Python variables behave like var for instance. God only knows how C++'s capture works. Best to avoid defining closures in loops in the first place.