Https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/es6/compare-scopes-of-the-var-and-let-keywords

Tell us what’s happening:
I am having difficulty in understanding the exercise , why are you using function inside for loop .

When i simply assign printNumTwo = i , the result is 2 but using the function gives 3, Why?

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

Hey man,
I don’t understand, what function?
In explaining the scope challenge, the variable will have different assignments depending on the placement of the variable in your code.

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

In this code the result for printNumTwo is 2. ( Correct ) But it doesn’t solution the challenge.

I mean when you replace the line
printNumTwo = i;

console.log(printNumTwo) // 2

With the function like this
printNumTwo = function () {
return i;
}
console.log(printNumTwo()) //3

You get different results.

Hey @munish259272!

I am going to post the full code with comments using var.

var printNumTwo;
for (var i = 0; i < 3; i++) {
  if (i === 2) {
    printNumTwo = function() {
      return i; // at this point i=2. But we are not done yet. 
// we still have to increment by 1 and check the condition in the for loop
// i++ 
// now i=3
// check the condition (is 3 < 3). Since the answer is no then we exit the for loop.
    };
  }
}
console.log(printNumTwo());

// Unfortunately, when you use var it updates the global variable meaning that i=3 not 2. 

This is why you should not use var anymore and instead use let. When you declare a variable inside a for loop using let it is only declared in the loop not globally.

In your first example

var printNumTwo;
for (var i = 0; i < 3; i++) {
     if (i === 2) {
        printNumTwo = i;
       }
}
console.log(printNumTwo); 
// now you are assigning the current value of i (2) to the variable called printNumTwo and logging it to the console. 
//when you add the function back in and increment by 1 like we did before then i=3.  Hopefully you see the difference now. 

Also, when you post to the forum, you will receive more responses if you place the link to the challenge in the body of the message and specify that you are asking a question about one of the sample problems.

Hope that helped!

1 Like