javascript

Closures


 

Closure is indeed a feature that allows inner functions to access variables from their containing lexical scope (the scope in which they are defined), even after the outer function has finished executing. This binding of a function to its outer scope is created automatically whenever a function is defined.

 

A closure "closes over" its outer scope, capturing references to the variables it needs, which enables it to access those variables even when invoked outside of its original lexical scope. This behaviour is fundamental to many JavaScript programming patterns, including encapsulation, private variables, and maintaining state.

 

Example:

function outerFunction() {
    let outerVariable = 'I am from outerFunction';

    function innerFunction() {
        console.log(outerVariable); // innerFunction has access to outerVariable
    }

    return innerFunction;
}

let myClosure = outerFunction(); // Invoking outerFunction returns innerFunction
myClosure(); // Output: 'I am from outerFunction'

 

Explanation:

InnerFunction retains access to outerVariable even though outerFunction has finished executing. This is an example of closure in action, where innerFunction maintains a reference to outerVariable from its outer lexical scope.