Javascript: Closure
Published on October 15th, 2019
Closures
"A closure is the combination of a function bundled together (enclosed) with references to its surrounding state (the lexical environment)".
Source: https://medium.com/javascript-scene/master-the-javascript-interview-what-is-a-closure-b2f0d2152b36
A closure it nothing more than a function with access to the variables from another function's scope.
That is done by creating a function inside another one.
The inner function has access to the outer one scope.
Even after the outer function is called, the outer scope will not be destroyed if the inner is referenced.
This way, that scope is accessible only, by the inner function, crearing data protection.
All changes to the outer scope variables will persist and be shown on each subsequent call.
Highlights:
- Closure are inner functions inside outer functions with access to the outer scope;
- The outer scope is not destroyed while the reference for the inner function exists;
- The outer scope variables changes will persist to subsequent call.
Why is it important?
- To store private data (not only a private convention like the underscore suffix)
- To build iterators
- To implement Singleton (single instance of an object while execution of the problem) -> Just have a nameless outer function in order not to be called directly.