-1

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

output : 2

How is this output become 2; explain what is happening inside the loop and scope of let.

Iłya Bursov
  • 23,342
  • 4
  • 33
  • 57
V V ARJUN
  • 3
  • 3

4 Answers4

1

It's simply because the only wait for the printNumTwo variable to hold a function which return the value of i (i==2) is only when the i counter is equal to 2 otherwise nothing is executed. for all other value of counter i the printNumTwo will not be touched. That's the main reason.

Yves Kipondo
  • 5,289
  • 1
  • 18
  • 31
1

Well basically it is looping and i is how many times its looped in simple words. So in your case, i starts at 0 and goes to 3, meaning it will loop 3 times. And you made an if statement inside which is:

if (i === 2) {//do stuff}

It basically just checked that if i is 2 - or that its the second loop, it will run. So when it was the second loop, it console logged 2 by the code you wrote:

printNumTwo = function() {
  return i;
};

And then printNumTwo was console logged (printNumTwo was i, or, 2). I hope that made sense.

Vivaan4
  • 95
  • 8
0

Because this code return i when its equal to 2 and by calling the printNumTwo() function, it also returns 2 because the code stopped the loop by returning it .

0

Because your using a for loop with a iterator variable that increments its value and stops until its stopping condition is met. Your global scoped variable has a value of the returned function which returns the iterators value.