To understand closure, let's take a look at the term Lexical scope.
Lexical scope of a function comprises of inner scope of function and ability to access its nearest surrounding environment
- The access ability is a hidden feature that cannot be access normally as object in JS (some says it's optimization engine from V8)
function outerFunc() {
let counter = 0;
return function inc() {
counter++;
}
}
// - the inc()'s lexical scope is its inner scope
// (within the {...}) and the ability to
// bound out and search for the counter;
- Once the
inc()
is returned to an instance, it encapsulates thecounter
value and bring it along - to a permanant memory, which means any of it instance from the same invocation can access tocounter
const newFunction = outerFunc();
newFunction(); // counter = 1
newFunction(); // counter = 2
- Different invocations can not share the same reference to
counter
const newFunction = outerFunc();
newFunction(); // counter = 1
newFunction(); // counter = 2
const anotherFunc = outerFunc();
anotherFunc(); // counter = 1, not 3
anotherFunc(); // counter = 2
anotherFunc
creates new Execution context, and the counter
is set to 0
in that new EC.
When a function is invoked, it firstly search for its inner local memory (inner scope), then if not found it will populate to its encapsulated memory, then if not found, it gradually bounce back to the broader nearest scope.
Source: Closure - Javascript.info
In short:
- Lexical scope: the inner scope and ability to access surrounding scopes (this is called Closure) ;
References
- Variable scope, closure
- JS the hard parts - Frontend master course
Top comments (2)
Thank you 🥰