What is a closure?

A JavaScript closure is a function together with the lexical environment in which it was declared. In plain terms, a closure lets an inner function access variables from an outer function even after the outer function has finished executing.

Closures are created whenever you define a function inside another function. The inner (child) function retains access to the outer function's variables, while the outer function cannot access variables declared inside the inner function.

Example: simple closure

7


function outer(){
    var x=3;
    function inner(){
        var y=4;
        return x+y;
    }
    return inner;
}

console.log( outer()() )

In the example above, the returned inner function still has access to x because the JavaScript engine keeps the variable in the lexical environment. This pattern enables private state and factory functions.

Common uses: data encapsulation, creating factories, and implementing private variables.


Lexical environment

Lexical environment refers to the mapping of variable names to their values in the scope where a function is declared. Variables declared in an outer function are accessible to inner functions via the scope chain.

Lexical environment of the outer function


function outer()
{
    var x=3;
    function inner(){
        var y=5;
        return x+y;
    }
}

Lexical environment of the inner function


function outer()
{
var x=3;
function inner(){
    var y=5;
    return x+y;
}
}

Closure scope

Closures interact with different levels of scope. In practice you will commonly see:

  1. global scope (variables declared outside any function)
  2. enclosing function scope (variables declared in parent/outer functions)
  3. local scope (variables declared inside the current function)

12


var x=3; // global

function outer(){
    var y=4;    // function

    function inner(){
        var z=5;    // local
        return x+y+z;
    }

    return inner;
}
console.log( outer()() )