Can someone help me understand why the variable printNumTwo is supposed to be equal to 3 and not 2?
In the example text for this challenge, the code snippet is given below:
var printNumTwo;
for (var i = 0; i < 3; i++){
if(i === 2){
printNumTwo = function(){
return i;
};
}
}
console.log(printNumTwo());
// returns 3
It is stated that, “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.”
I don’t understand why printNumTwo would not be equal to 2. I thought the variable printNumTwo only gets assigned a specific value once and that is when i === 2. printNumTwo is never set equal to a specific value at any other time, regardless of i, correct?
Thank you in advance!
Your browser information:
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3559.6 Safari/537.36
.
Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/es6/compare-scopes-of-the-var-and-let-keywords