Great question! It made me really think. I would like to add a little something, if I may, that helped me understand the code.
The JS engine will read the keyword ‘var’ on the variable name printNumTwo, and so ‘printNumTwo’ is placed in ‘global’ memory in the execution environment, or memory heap. That is the nature of the infamous var.
As we know, JS is a single-threaded language,meaning the engine reads code, ‘line-by-line’, from top-to-bottom.
When the JS engine gets to the for…loop ‘conditional statement’
i < 3000;
as we know, it’s true, and heads to the next line of code.
Since ’ i ’ was declared with keyword var inside the for-loop, when the JS engine has finished the conditional evaluation, it goes to the next line which is the if statement. When the JS engine parses the ’ i ’ inside the if conditional
if ( i === 2) {
it looks for i in memory. It finds it in global memory having been assigned to the ’ var ’ in the for-loop’s variable ‘i’ declaration with a value of 0
. It returns back up in the for-loop, having retrieved the ‘i’ s value from global memory. The ‘var’ has done it’s work. It will just keep evaluating the for-loop conditional, then parses the i in the if statement, then back into the for-loop and, keeps incrementing until 30000< 30000 returns a falsy. This ‘breaks’ the JS engine out of the for-loop and down to the function call.
console.log(printBumTwo());
var printNumTwo; // globally scoped
for (var i = 0; i < 30000; i++) {
if (i === 2) {
printNumTwo = function() {
return i;
};
}
}
console.log(printNumTwo());
// returns 30000
When the function is invoked, the JS engine creates a new function execution context. The printNumTwo() gets placed on the call-stack. The ‘return’ statement is read by the JS engine; "return the value of i and exit the function, and, please, pop the function off the call-stack. Get to work! The engine looks for i in the context of it’s execution environment. It’s not found i in the block scope of the function, so it looks it looks up the chain, and finds it in the global memory. It returns the value of i, 30000.
You can see this in the Chrome developer tools if you debug this code.
I read all the reply’s and learned from this great question.
I changed the ‘var’ to let in the for-loop.