Closures

Closures are the combination of function and lexical scope.

Closure allows the function to access the variables from the closing scope after leaving its scope in which it was declare.

Closure is a function that return a function(HOF).

Ex:
const a = () => {
    let grangpa = 'grandpa';
    return function b() {
        let father = 'father';
        return function c() {
            let son = 'son';
            return `${grangpa} > ${father} > ${son}`;
        }
    };
};

const one = a(); // [Function b]
const two = one(); // [Function c]
const three = two(); // grangpa > father > son

When the function a is executing grandpa variable is created in its variable environment. After the execution completed, before removing the variables it will checks for its reference in its child functions. If it is exist in its child it will not be removed. So it can be accessed by its child functions.

Last updated