Help ! ES6: Compare Scopes of the var and let Keywords

cannot understand why it returns 3 because function should stop when it returns therefore printing 2

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

Declare your loop variable as let

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

The function shouldn’t stop when i === 2, it simply assign an anonymous function to the variable printNumTwo^^

The problem with var is that it has a global scope, therefore even though the assignment has been done when i === 2 , when you call the function i === 3 ^^

4 Likes

I want to understand how this code is working

oh I thought the function will execute there and then only , thanks now I got it

2 Likes

@Advitya-sharma Just as @Layer had mentioned. The problem is that you declare your loop variable with var which has global scope (meaning it can be over-ridden without JS throwing an error). This is the cause for i === 3 on your second method call.

2 Likes

@Layer and @Dutchman

Interesting topic. I hope it´s OK if I ask a related follow up question.

Would another way of putting it be that when you console.log printNumTwo() at the end, it will start the anonymous function where i initially was 2. But since the loop continued after the variable printNumTwo got assigned an anonymous function, i is now 3 and the loop is finished. Therefore printNumTwo is in a way forced to display the more updated global variable i, which now is 3.

3 Likes

@jjberg83 Well said. And this event is happening due to the nature of variables declared with var having global scope.

2 Likes