var printNumTwo;
for (var i = 0; i < 3; i++) {
if (i === 2) {
printNumTwo = function() {
return i;
};
}
}
console.log(printNumTwo());
I’ve got 3 questions:
1- I did not understand how a function can be defined without a name and on top of that assigned to a variable, in this case how is it being called? Is it being called at the same time of definition?
2- If we were to replace the var keywords with let keywords and define the i variable globally outside the door loop, we would get the same result, right? Apart from this question, from what I understood: the i variable is defined globally because we’re using the var keyword, but I am not getting how that results in number 2 being returned. Shouldn’t the code iterate through the loop with the values of i being [0, 1, 2] one of them , for each iteration and exit the loop with the global variable i being equal to 3? The only time in the loop shall the code execute the code inside the if statement is when i equals 2, and assigning the variable printNumTwo the returned i in the function which in this case is 2, and there are no other assignment statements changing the value of this variable nor should we go in any other iteration executing the code in the if statement and changing the value of the variable printNumTwo.
3- What does the tutorial mean by block, statement or expression in the paragraph below? What is the example for each one of these three, and how are they different from each other?
The
let
keyword behaves similarly, but with some extra features. When you declare a variable with thelet
keyword inside a block, statement, or expression, its scope is limited to that block, statement, or expression.
Challenge: Compare Scopes of the var and let Keywords
Link to the challenge: