0

I am newer to learning javascript and still working through the basics. I'm also trying to wrap my head around some of the logic and wanting to make sure I clearly understanding the basics, before moving on to more difficult programming.

As I was learning, one of the things discussed was the var keyword's scope and the issues it can pose when declared globally. This code was given as an example:

`

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

`

The console output for printNumTwo() is 3. However, I'm not understanding why this occurs.

This is what I'm getting from the code. The global variable is declared, but is undefined. However, the for loop would run and start at 0. 0 would fail the if statement, then the for loop would run again with i = 1. This would fail the for loop. Then the loop would run with i = 2, which would pass the for loop. This would then search in the global scope for a variable called printNumTwo and declare it, again, as a function that returns the i value. And, at that point, wouldn't the i value be 2?

I would appreciate any and all help to better understand why the output is 3 and what causes this to happen. Thank you!

  • The loop only stops when `i < 3` that means it stops when `i` becomes `3`. The last value of `i` will be `3` hence the output of the code. – Titus Dec 11 '22 at 11:53

0 Answers0