DEV Community

Discussion on: What the Hell is Closure in JavaScript?

 
jonrandy profile image
Jon Randy πŸŽ–οΈ • Edited

Every function forms a closure with the lexical scope in which it was created. If a variable changes in that lexical scope, it will see the changed value. Make a JS module, export a function that accesses a module level var - this, again, works due to closures. Change the module level var, the change will be reflected. Often when code takes advantage of closures, it does so within the lexical scope of another function, which it still has access to when that function finishes execution. Closures work the same everywhere.

Your example with the global scope just reinforces the point. The global scope is still active and accessible, so vars there can be easily changed.

Variables are not 'stored' in a closure, a closure has references to the function's lexical scope.