Where is declared the printNumTwo function?

Tell us what’s happening:

I don’t understand why this returns 3. The exercise explains but I still cannot figure it out.

Where is declared the function named printNumTwo() ?
I dont see a declaration like: “function printNumTwo(){
}” - I see a var declaration named printNumTwo, not a function.

i starts on 0. So, the if compares with 2: not the same, then it doesn’t gets into the “if” statement. Then i is 1, again, not equals to 2, doesn’t gets into the “if” statement. But when it worths 2, the “if” compares and it is equal, so it gets into the “if” statement and makes the printNumTwo var equals to “function()”. THIS IS THE PART I DON’T UNDERSTAND. What is “function()”? Where does it comes from? Why you didn’t explain this before? Why without a name? To which function is pointing?

Your code so far

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

As you can see, printNumTwo() prints 3 and not 2. This is because the value assigned to i was updated and the printNumTwo() returns the global i and not the value i had when the function was created in the for loop.




Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.149 Safari/537.36.

Challenge: Compare Scopes of the var and let Keywords

Link to the challenge:

It is declared here:

printNumTwo = function() {
  return i;
};
console.log(printNumTwo)
ƒ () {
  return i;
}

It’s a function expression using an anonymous function (look at the name part of the function definition explanation).

The variable i is global and what gets printed is the last value it was set to in the loop.

There are a bunch of threads on this challenge, I’d suggest checking them out.
http://forum.freecodecamp.org/search?q=Compare%20Scopes%20of%20the%20var%20and%20let%20Keywords
http://forum.freecodecamp.org/search?q=printNumTwo

1 Like