0

I'm new to javascript closures. My question is, in the SO post about javacript closures, the first code block

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]();
}

outputs

My value: 3

My value: 3

My value: 3

But how is it that when I re-use i variable in the second for loop, there is no closure?

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 i = 0; i < 3; i++) {
  // and now let's run each one to see
  funcs[i]();
}

How is the output in the second code block

My value: 0

My value: 1

My value: 2

Arunster
  • 185
  • 1
  • 8
  • 1
    The answer seems pretty clear--you're logging `i`, and in the first case it's always 3 while in the second case it's reset to 0 and counts up to 3. In both cases, it's probably an unintended result. If you use `let` instead of `var` there's no confusion. – ggorlen Jun 26 '20 at 03:43
  • @ggorlen, I read the answer, and it doesn't quite answer my question: how is `i` captured in the first block different from the `i` captured in the second block? – Arunster Jun 26 '20 at 03:50
  • I'm not sure what you mean--it's not different. That's the whole problem with `var`, it creates variables that aren't scoped to the block. – ggorlen Jun 26 '20 at 04:07
  • 1
    In both examples, you're using the same `i` variable declared at the first loop. But in the second example, you reset the `i` variable to `0`, so what is its value on the first iteration of the second loop? It's `0`. You then increment it to `1`. So what's its value a the second iteration of the second loop? It's `1`.. and so on. –  Jun 26 '20 at 04:16
  • 1
    ...you may be less confused if you move the `var` declaration of `i` to the very top of the code. That's actually where it takes place, irrespective of where you put `var`, and of how many times you re-declare it. –  Jun 26 '20 at 04:16

1 Answers1

0

Use let keyword for variables declared inside for loops(let i, let j). Its working

sonEtLumiere
  • 4,461
  • 3
  • 8
  • 35