Closures in Javascript example!

Javascript Closures in English simplified!

credit

A closure is a feature in JavaScript where an inner function has access to the outer (enclosing) function’s variables!

Here is an example of a very uncommon closure in javascript:


const name = 'Mohammad Ali';

function innerFunction(){
    console.log(name);
}

innerFunction();

The function innerFunction() has access to the variable name. The outer scope of the file in which the code resides, while there is no explicit function declaration - the function innerFunction() having access to a variable name satisfies the condition of a inner function having access to an outer scope variable.


function outerBodyFunction() {
    const name = 'Mohammad Ali';

    function innerFunction(){
        console.log(name);
    }

    return innerFunction;
}

let _innerFunction = outerBodyFunction(); // or outerBodyFunction()();
_innerFunction();

The function innerFunction() has access to the variable name. The outer scope of the outerBodyFunction function in which the code resides, the function innerFunction() having access to a variable name satisfies the condition of a inner function having access to an outer scope variable.



Nordible is a digital solutions provider helping organizations achieve their digital goals.

We develop and measure digital solutions, implement impactful brand promotion and SEO strategies and develop software driven by rigorous testing that help your business succeed online and beyond.

You can contact us at info@nordible.com for business inquiries.

Follow us: