ES6: Compare Scopes of the var and let Keywords Example Code

I’m not sure how the example code works in this tutorial. What happens when i = ==2? When the program reaches the line printNumTwo = function() {return i;}, what becomes printNumTwo? In other words, why isn’t the result of function () {return i;} = 2? What exactly is happening?

Your code so far


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


Your browser information:

User Agent is: Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:71.0) Gecko/20100101 Firefox/71.0.

Challenge: Compare Scopes of the var and let Keywords

Link to the challenge:

Because i is declared using var it exists outside of the for loop. You could just as well write:

var i;
for (i = 0; i < 3; i++) {
   ...
}

Basically, i is acting as a global variable for both the for loop and the printNumTwo function. So when you finally get around to calling the printNumTwo function, the value of i is the last value it was set to in the for loop, which is 3 in this case.

Right, but when (i ===2 ) and the if statement condition becomes true is function () {return i;} not being executed?

Nope. The function is only being defined there (or whatever Javascript calls that mess). The point here is that var lets bad things like this happen so never ever use var.

1 Like