Logo
HTMLCSSJavaScriptReactjsnewContactUpdates

Get started today

HTMLCSSJavaScriptReactjsnewContactUpdates

Tools

Resume BuilderQR GeneratorVS Code Editor

Connect

GitHubWhatsApp Channel
lexical scope
interview questions

Javascript Closure

By Saket Bhatnagar•May 1, 2023•Beginner to Intermediate

Table of Contents

  1. Closure

Closure

  1. 1A closure is a memory block that stores the state (variables) and behavior (functions) of a parent function, so that a child function can access them even after the parent function has finished executing.
  2. 2Closures are created automatically when a function is defined inside another function and references variables from the outer (parent) function.
  3. 3They allow the inner function to access the parent function variables even after the parent function has finished executing.
  4. 4Closures are powerful for preserving data without using global variables or classes (because class are function in javascript).
  5. 5Each time the outer function is called, a new closure (memory scope) is created.
  6. 6The child function keeps a reference to the outer function’s variables — not a copy — so the values remain live and can be updated.
  7. 7Real-life analogy: Imagine a parent owns a plot of land (variables and logic). When the parent gives parts of the land to their children (functions), each child carries their portion and the tools (behavior) needed to manage it. Even if the parent is no longer around, the child still owns and works their land. This is how closures preserve data and behavior.
  8. 8Another example: Think of a bank account as a closure — it holds a private balance and provides deposit, withdraw, and checkBalance functions. Each account holds its own state and cannot affect other accounts.
  9. 9Example:

    Closure Example: Bank Account

    1function createBankAccount(initialBalance) {
    2 let balance = initialBalance;
    3
    4 return {
    5 deposit: function(amount) {
    6 balance += amount;
    7 return `Deposited ${amount}. New balance: ${balance}`;
    8 },
    9 withdraw: function(amount) {
    10 if (amount > balance) {
    11 return "Insufficient funds!";
    12 }
    13 balance -= amount;
    14 return `Withdrew ${amount}. New balance: ${balance}`;
    15 },
    16 checkBalance: function() {
    17 return `Current balance: ${balance}`;
    18 }
    19 };
    20 }
    21
    22 const account1 = createBankAccount(1000);
    23 const account2 = createBankAccount(500);
    24
    25 console.log(account1.deposit(200)); // Deposited 200. New balance: 1200
    26 console.log(account2.withdraw(100)); // Withdrew 100. New balance: 400
    27 console.log(account1.checkBalance()); // 1200
    28 console.log(account2.checkBalance()); // 400
    💡

    Note

    Note: Each call to createBankAccount creates a new closure with its own balance. The state is preserved separately.
  10. 10Explanation: Even though the outer function createBankAccount has finished executing, the returned inner functions have reference of closures stored in memory and use the balance variable. Separate closure is created for each call to createBankAccount and it is stored in memory. This is how data privacy is maintained.
  11. 11Advantage: Closures provide private, persistent memory for functions. They're useful in building encapsulated modules, counter functions, factory functions, and callback handlers.
  12. 12Disadvantage: Closures can lead to memory leaks if variables are retained unnecessarily (e.g., inside unused callbacks or event listeners).

Share this article

Last updated: May 1, 2025

Join Our Community

Login to Join

© 2025 Saket Bhatnagar. All rights reserved.

    ☕