Compare Scopes of the var and let Keywords

I don’t understand why the function “printNumTwo” returns 2, instead of 0 or undefined. Since i is only in the scope of the for, when the function is called the for has ended, so there wouldn’t be a variable i anymore.

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

It’s all about what JS calls “closures”. At the time the printNumTwo function is created the value of i is 2. Because you used let to declare i in the for loop then the printNumTwo function will remember that the value of i is 2 and that’s what it will return whenever you call it.

If you had used var instead to declare i in the for loop then printNumTwo would return 3 because that is the last value for i when the for loop stops.

Also, your last console log is an error because the variable i doesn’t exist outside of the for loop since you declared it with let.

3 Likes

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.