What is a Closure?

A closure (closureFn) are functions that have access to variables from an outer function even after the outer function has finished executing.

Closures are often used to create private variables and functions, allowing data encapsulation and data hiding in JavaScript.

How Closures Work

A closure is created when a function is defined inside another function. The inner function has access to the variables of the outer function even after the outer function has returned.

Example of Closure


function outerFunction() {
    let outerVar = 'I am from outer function';
    
    // Inner function (closure)
    function innerFunction() {
        console.log(outerVar); // innerFunction has access to outerVar
    }
    return innerFunction;
}
const closureExample = outerFunction(); // outerFunction returns innerFunction
closureExample(); // Output: 'I am from outer function'