In this example, taken from the W3Schools JS Tutorial, how is it possible for the variable n
to still be used in the next
function ?
// Home Made Iterable
function myNumbers() {
let n = 0;
return {
next: function() {
n += 10;
return {value:n, done:false};
}
};
}
// Create Iterable
const n = myNumbers();
n.next(); // Returns 10
n.next(); // Returns 20
n.next(); // Returns 30
I'm coming from a C/C++ background and the lifetime of this variable makes no sense to me. It seems to behave like a global static variable but it should have been deleted when exiting myNumbers()
, especially when declared with the let
keyword. How can, then, the next
method uses it without raising a ReferenceError
and keeping its value updated ?