0

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 ?

1 Answers1

1

Because of a closure feature of the JavaScript, keep the variable accessible even if the containing function died, whenever there is a child function still need to access it.

For more resources.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures

Mina
  • 14,386
  • 3
  • 13
  • 26