DEV Community

Cover image for Closure in JavaScript
Vigneshwaran V
Vigneshwaran V

Posted on

Closure in JavaScript

A closure in JavaScript is the combination of a function bundled together with references to its surrounding state, known as the lexical environment. In simpler terms, a closure allows an inner function to remember and access variables from its outer (parent) function's scope, even after the outer function has completely finished executing.

  • Every time a function is created in JavaScript, a closure is automatically created alongside it.

Why is Closure Used?

  • Preserve data between function calls

  • Create private variables

  • Avoid polluting the global scope

  • Implement function factories

  • Maintain state in asynchronous operations

Example

function bankAccount() {
    let balance = 1000;

    return {
        deposit(amount) {
            balance += amount;
            console.log(`Balance: ${balance}`);
        },

        withdraw(amount) {
            balance -= amount;
            console.log(`Balance: ${balance}`);
        },
        getbalance(){
            console.log("Balance: ",balance);
        }
    };
}

const account = bankAccount();

account.deposit(500);   // Balance: 1500
account.withdraw(200);  // Balance: 1300
console.log(account.balance);  //undefined (it is a private variable)
account.getbalance(); // Balance: 1300
Enter fullscreen mode Exit fullscreen mode

Output

Balance: 1500
Balance: 1300
undefined
Balance: 1300
Enter fullscreen mode Exit fullscreen mode

Advantages of Closures

1. Data Privacy
Variables can be hidden from outside access.

function secret() {
    let password = "1234";

    return function () {
        console.log(password);
    };
}
Enter fullscreen mode Exit fullscreen mode

2. Maintain State
A function can remember previous values.

function createCounter() {
    let count = 0;

    return function () {
        return ++count;
    };
}

const counter = createCounter();

console.log(counter()); // 1
console.log(counter()); // 2
console.log(counter()); // 3
Enter fullscreen mode Exit fullscreen mode

3. Avoid Global Variables
Without closure:

let count = 0;
Enter fullscreen mode Exit fullscreen mode

With closure:

function counter() {
    let count = 0;
}
Enter fullscreen mode Exit fullscreen mode

Keeps variables local and prevents accidental modification.
4. Function Factories
Closures can generate customized functions.

function multiplyBy(num) {
    return function (value) {
        return value * num;
    };
}

const double = multiplyBy(2);
const triple = multiplyBy(3);

console.log(double(5)); // 10
console.log(triple(5)); // 15
Enter fullscreen mode Exit fullscreen mode

Here, each returned function remembers its own num.


Closure means a function "remembers" the variables of its parent function even after the parent function has completed execution.


Closures provide

  • Access to parent scope variables.

  • Variables remain alive after the parent function ends.

  • Data privacy (private variables).

  • State management.

  • Less use of global variables.

  • Function factories.

  • Useful for callbacks, timers, and event handlers.


Lexical Scoping

  • Closures rely on lexical scoping, which means a functionโ€™s scope is determined by where it is defined, not where it is executed.

  • A function retains access to the scope where it was defined.

  • Inner functions can access outer function variables.

  • Enables closures to โ€œrememberโ€ their environment.

A closure is a function that remembers and accesses variables from its outer scope even after the outer function has finished executing, enabling data privacy, state preservation, and function customization.


References

https://www.w3schools.com/js/js_function_closures.asp
https://www.geeksforgeeks.org/javascript/closure-in-javascript/

Top comments (0)