0

This is the code of which i am not able to understand the flow of and also how the value of i persist even after the for loop ends.

var printNumTwo;

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

console.log(printNumTwo());

The output of the program is

0
1
now
2
2
3
4
inside
2

adiga
  • 34,372
  • 9
  • 61
  • 83
bhoomeendra
  • 197
  • 1
  • 8
  • JS Closure here !!! – Shubham Dixit Dec 12 '19 at 10:51
  • 1
    `i` is declared with `let`, so it has block scope inside the loop - every iteration has a separate binding for `i`, and the iteration that has a function assigned to `printNumTwo` is when the `i` is `2` – CertainPerformance Dec 12 '19 at 10:51
  • Reopening because the dup you marked does not use `let` and thus does not explain this particular example. This question deserves its own answer for its own circumstances. – jfriend00 Dec 12 '19 at 10:53

1 Answers1

1

reason of this behavior is Closures

A closure gives you access to an outer function’s scope from an inner function. In JavaScript, closures are created every time a function is created, at function creation time. mozilla doc

var printNumTwo;

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

console.log('now calling printNumTwo()')
let s=printNumTwo();

console.log('now printing return value of printNumTwo()')

console.log('retrun value of PrintNumTwo is:'+s);
Jadli
  • 858
  • 1
  • 9
  • 17