(Compare Scopes of the var and let Keywords) I don't understand this statement:

JavaScript Algorithms and Data Structure
Lesson 1: Compare Scopes of the var and let Keywords

I don’t understand this statement:

printNumTwo() returns the correct value (2) because three different i variables with unique values (0, 1, and 2) were created by the let keyword within the loop statement.

Why three different i variables?
Not one?

let printNumTwo;
for (let i = 0; i < 3; i++) {
  if (i === 2) {
    printNumTwo = function() {
      return i;
1 Like

Hi! not sure why says three different variables were created, i suposse that is a writing error and they want to say that the i variable has been update with three differents values. But its just one variable.

I think it’s OK to think of it as three different i variables in this context. Each time through the for loop, the value of i is only good for that loop. So it’s as if a new i variable is being created just for that time through the loop. That’s what the example code is demonstrating. Even though you went through the for loop three times and it ended when i is 3, the printNumTwo function still returns 2 because that was the value of i during that time through the loop. So it’s as if each loop has it’s own i.


I understand the same, but it seems we are wrong. :thinking: :slightly_smiling_face:
Thank you anyway! :+1: :+1: :+1:

It seems that you are right. I have never seen it that way. Thanks. :raised_hands:

4 posts were split to a new topic: Why use let in a for loop?

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