«Back to Home

Learn JavaScript

Topics

Closures in JavaScript

Closures are one of the most important and powerful concepts in JavaScript.
They help functions remember variables even after the outer function has finished running.

Many students find closures confusing at first, but with simple examples, they become easy to understand.

Closures are heavily used in:

  • Functions inside functions

  • Keeping data private

  • Event handlers

  • Callback functions

  • Factory functions

  • Maintaining state

  • Interview questions

Let’s break closures down in the simplest way possible.

What Is a Closure?

A closure is created when:

  • A function is defined inside another function, and

  • The inner function remembers the variables of the outer function,

  • Even after the outer function has completed execution.

Simple Definition:

A closure = function + outer scope variables.

Example 1: Basic Closure

function outer() {
    let name = "Aman";

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

    return inner;
}

let fn = outer();  
fn();

Output:

Aman

Why does this work?

  • outer() finished running

  • But inner() still remembers the variable name

  • This memory retention is called closure

Example 2: Closure With Counter (Very Important)

Closures can help keep variables private.

function counter() {
    let count = 0;

    return function() {
        count++;
        console.log(count);
    };
}

let c1 = counter();
c1();
c1();
c1();

Output:

1
2
3

count is not accessible outside — it's private.
Only the inner function can modify it.

This is how real applications create private variables.

Example 3: Multiple Independent Closures

let c1 = counter();
let c2 = counter();

c1(); // 1
c1(); // 2

c2(); // 1

Each counter has its own private count.

Example 4: Passing Values to Closures

function greet(message) {
    return function(name) {
        console.log(message + ", " + name);
    };
}

let sayHi = greet("Hi");
let sayHello = greet("Hello");

sayHi("Riya");
sayHello("Aman");

Output:

Hi, Riya
Hello, Aman

The inner function remembers the variable message.

Example 5: Closure in a Practical Use Case — Discount Calculator

function discountCalculator(rate) {
    return function(price) {
        return price - (price * rate);
    };
}

let discount10 = discountCalculator(0.10);
let discount20 = discountCalculator(0.20);

console.log(discount10(100)); 
console.log(discount20(100));

Output:

90
80

Real-world use cases: ecommerce, billing, finance.

Example 6: Closure with setTimeout (Famous Interview Question)

function delay() {
    let message = "Timer Finished";

    setTimeout(function() {
        console.log(message);
    }, 1000);
}

delay();

Even after delay() is finished, the inner function remembers message.

Why Are Closures Useful?

  1. Data Privacy
    Variables stay hidden from outside.

  2. Maintaining State
    Counters, toggles, progress bars, etc.

  3. Function Factories
    Create multiple reusable functions.

  4. Callbacks and Event Handlers
    Closures help store values for later.

  5. Interview Questions
    Closures are a popular topic!

Common Mistakes Beginners Make

  1. Thinking the outer function must be running for closure to work

  2. Accessing private variables directly (not allowed)

  3. Forgetting that each closure has its own copy of variables

  4. Using var inside loops without understanding closure behavior

  5. Confusing scope with closure

Example Program (Complete Closure)

function bankAccount() {
    let balance = 1000;

    return {
        deposit(amount) {
            balance += amount;
            console.log("Balance:", balance);
        },
        withdraw(amount) {
            balance -= amount;
            console.log("Balance:", balance);
        }
    };
}

let account = bankAccount();

account.deposit(500);
account.withdraw(200);

Output:

Balance: 1500
Balance: 1300

Here, balance is private — closure protects it like a real bank account.