I really don't know which "i" var was globally defined to result in 3 ? Please help me clarify this!

Tell us what’s happening:
Describe your issue in detail here.

  **Your code so far**

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


output: 3
      **Your browser information:**

User Agent is: <code>Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/101.0.4951.54 Safari/537.36</code>

**Challenge:**  Compare Scopes of the var and let Keywords

**Link to the challenge:**
https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/es6/compare-scopes-of-the-var-and-let-keywords

You’ve modified the function so that it returns immediately. I don’t think you want to do that. Also, the instructions say “Be certain not to use the var keyword anywhere in your code.” but yet you are still using var to declare i in the foor loop. But there isn’t even a for loop in the original code so you shouldn’t have added it for your solution.

I would click the “Reset All Code” button to get a fresh start on this challenge. The instructions say “This exercise is designed to illustrate the difference between how var and let keywords assign scope to the declared variable.” So I would bet that there is a good chance you should be using let in your solution.

1 Like

thanks for your reply. Actually, I’m getting in trouble with the example in the tutorial, not the exercise. So I use that example code to post, and ask everybody to help me understand the nature of why output is 3 and which ‘‘i’’ is assigned by 3.

In that example there is only one i variable. It is declared in the for loop statement. But it is declared using var which means it is basically a global variable. If you understand how a for loop works then you will know what the value of i is after the loop has exited. Do you understand why the value of i is 3 after the loop has finished? When printNumTwo is called, it is returning the value of i, which again, is a global variable and thus it also returns 3.

1 Like

oh thank you so much. I totally get it !

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