0

I was researching var vs. let and I stumbled upon a question containing this code

var funcs = [];
// let's create 3 functions
for (var i = 0; i < 3; i++) {
  // and store them in funcs
  funcs[i] = function() {
    // each should log its value.
    console.log("My value: " + i);
  };
}
for (var j = 0; j < 3; j++) {
  // and now let's run each one to see
  funcs[j]();
}

The output confused me, it was

My value: 3 My value: 3 My value: 3

instead of

My value: 0 My value: 1 My value: 2

The top answer for this question says

Well, the problem is that the variable i, within each of your anonymous functions, is bound to the same variable outside of the function.

Why is this? What is happening in the JavaScript engine that causes this?

Jordan Baron
  • 141
  • 1
  • 12
  • 4
    `console.log("My value: " + i)` is only evaluated when the function is called. And... you happen to call it when the first loop is over and `i` is 3. Since the variable is global, all your functions refer to the same `i` – blex Apr 15 '21 at 12:43
  • 3
    `var i` creates **one** variable instance which is global, so it will be settled to 3 when the first loop has finished. However if you would do `for (let i =......`, then the loop body gets a new `i` instance with block scope for each iteration, and then it will work as you expected. – trincot Apr 15 '21 at 12:45
  • The answers in that question give numerous explanations/ solutions – charlietfl Apr 15 '21 at 12:47
  • 1
    I've slightly re-written your snippet to hopefully provide you with a better picture of what actually happens. https://gist.github.com/3limin4t0r/84ed632cf114367c5f0e45a195e89faf – 3limin4t0r Apr 15 '21 at 12:54

0 Answers0