DEV Community

Hihi
Hihi

Posted on • Updated on

Javascript scope and closure

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;
Enter fullscreen mode Exit fullscreen mode
  • Once the inc() is returned to an instance, it encapsulates the counter value and bring it along - to a permanant memory, which means any of it instance from the same invocation can access to counter
const newFunction = outerFunc();

newFunction(); // counter = 1
newFunction(); // counter = 2
Enter fullscreen mode Exit fullscreen mode
  • 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
Enter fullscreen mode Exit fullscreen mode

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.

Function lexical ability
Source: Closure - Javascript.info

In short:

  • Lexical scope: the inner scope and ability to access surrounding scopes (this is called Closure) ;

References

Latest comments (2)

Collapse
 
Sloan, the sloth mascot
Comment deleted
Collapse
 
ngquan profile image
Hihi

Thank you 🥰