0

I don't understand why the behavior of the function is funny.

let printNumTwo;
for (let i = 0; i < 3; i++) {
  if (i === 2) {
    printNumTwo = function() {
      return i;
    };
  }
}
let i =5    
console.log(printNumTwo());

I thought the function is created globally and it will have to return 5. Why the function has small scope? Where could i read about what more. PS Sorry for my english and my probably stuped question. I need more understandable info for this TY

  • `let` has lexical scope and because of closure, it is returning 2. – Hassan Imam Mar 16 '21 at 18:21
  • 2
    You have there two different variables named `i`, one in the loop, and one after the loop. – Theraot Mar 16 '21 at 18:22
  • It doesn't matter that the `printNumTwo` variable is global, what matters is the function assigned to that variable, which is created within the `for` loop when `i` is 2. Since `i` is declared with `let` in the `for` construct, a different `i` is created for each loop iteration. The one that the function closes over is the one containing 2, so you see 2. The `i` at the end isn't used, the function closes over the `i` inside the loop. – T.J. Crowder Mar 16 '21 at 18:22
  • @Theraot - Good point. There are four: one each for the three loop iterations, and the fourth declared after the loop at the end. :-) – T.J. Crowder Mar 16 '21 at 18:23
  • Change both `let`s to `var`s and you'll get the desired behavior. This pushes the scoping of `i` to be global and avoids the redeclaration error caused by using two `let`s. Not that you'd want to do that in real code. – ggorlen Mar 16 '21 at 18:24
  • @ggorlen - If the OP changed `let` to `var`, they'd get an error because of the duplicated declaration. You can't declare `i` with `var` and also with `let` in the same scope (and of course, with `var`, it wouldn't be scoped to just inside the loop). :-) – T.J. Crowder Mar 16 '21 at 18:24
  • @ggorlen - Ah, fair enough. – T.J. Crowder Mar 16 '21 at 18:25

0 Answers0