Quote:
How does the func(); function retreive the variable "i"?
With the "return" statement, which returns a value to the caller:
var funcs = [];
for (let i = 0; i < 10; i++) {
funcs.push(function() { return i; });
}
funcs.forEach(function(func) {
var i = func();
console.log(i);
});
Quote:
When func() is run, does the code return to line 4, where the function was created?
Or is func() literally replaced with "console.log(a number)"?
You don't actually "return" to line 4: when you call
funcs.push(...)
, you create a new function that returns a value, and that value is what
i
is. So, once you are out of your
for
loops, your array contains 10 function definitions: a function that returns
0
, a function that returns
1
and so on. The
.forEach
iterates over all these functions one by one.
In your comment, you asked why it would always print "10" if you used
var
instead of let. The reason is
scope[
^] :
let
has block scope,
var
has function scope (or when defined outside a function, like here, global scope). So when you use
var
, then
i
will always be "the same i" because it has the same scope, which does not happen with
let
, because it has a different scope.