I get that i because of var is a global variable and if I try to access i’s current value after for loop finished … will get 3 , but don’t we have the condition i==2 that if only i=2 then the variable printNumtwo will get updated to 2 otheriwse we don’t update it…so how’s it 3?
var printNumTwo;
for (var i = 0; i < 3; i++) {
if (i === 2) {
printNumTwo = function() {
return i;
};
}
}
console.log(printNumTwo());
Challenge: ES6 - Compare Scopes of the var and let Keywords
Since we used the var keyword to define i, the algorithm doesn’t create a new i variable every time it loops. It just updates the value of that existent i variable.
What we’re really doing here is that we’re telling the computer that if the value of i hits 2, we want to make the printNumTwo variable store a function that returns the value of i.
So every time we call that function, it is going to check what value i has at that very moment we’re calling it, and return that value.
Since we only call that function in the console.log( ) after the entire loop has ended, the value of i has already been incremented to 3.
Maybe if you run the code below you’ll be able to see better how the value of i changes:
var printNumTwo;
for (var i = 0; i < 3; i++) {
if (i === 2) {
printNumTwo = function() {
return i;
};
console.log(printNumTwo());
}
}
console.log(printNumTwo());
It first logs the function right after it is created and then again when the loop has ended.
okay but are’t we only updating the value of var printNumTwo only when condition i==2 is met …when i reaches 3 shouldn’t it be unable to update the variable further since condition isn’t met ?
The way function calls work is that it is going to execute the code inside the function. It doesn’t care about the conditions that needed to be met for the function to be created.
Inside the printNumTwo() function, all we’re doing is returning the value of i. So when we call the function it is going to only execute the line
which is going to see what value i has at that very moment and return it.
Since the value of i has been updated to 3 before we called the function. The returned value will be 3.
It won’t care about what value i had when printNumTwo was first assigned to that function, because that value has already been changed.