DEV Community

Cover image for πŸ”’ JavaScript Closures: A Complete Guide with Examples, Pros & Cons
ROHIT SINGH
ROHIT SINGH

Posted on

πŸ”’ JavaScript Closures: A Complete Guide with Examples, Pros & Cons

πŸ“Œ Introduction

JavaScript is known for its flexibility and powerful features. One of the most important β€” yet often confusing β€” concepts is the Closure.

Closures are used everywhere in modern JavaScript frameworks (like Angular, React, Node.js) and mastering them is essential for writing clean, optimized, and reusable code.

In this blog, we’ll explore:

  • What closures are
  • How they work with examples
  • Real-world applications
  • Advantages & disadvantages

🧩 What is a Closure in JavaScript?

A closure is created when a function β€œremembers” the variables from its outer scope, even after the outer function has executed.

πŸ‘‰ In simple words:
Closures give you access to an outer function’s scope from an inner function, even after the outer function is gone.

πŸ”¨ Closure Example

function outerFunction() {
  let counter = 0; // outer scope variable

  function innerFunction() {
    counter++; 
    console.log(counter);
  }

  return innerFunction;
}

const increment = outerFunction(); // outerFunction executed
increment(); // Output: 1
increment(); // Output: 2
increment(); // Output: 3
Enter fullscreen mode Exit fullscreen mode

πŸ“ Explanation

outerFunction() defines counter and returns innerFunction.

Even after outerFunction has finished execution, innerFunction still remembers the variable counter.

That’s a closure in action.

🌍 Real-Life Applications of Closures

  1. Data Privacy / Encapsulation

You can use closures to keep variables private and inaccessible from the outside world.

function createBankAccount(initialBalance) {
  let balance = initialBalance;

  return {
    deposit(amount) {
      balance += amount;
      return balance;
    },
    withdraw(amount) {
      if (amount <= balance) {
        balance -= amount;
        return balance;
      } else {
        return "Insufficient funds!";
      }
    },
    getBalance() {
      return balance;
    }
  };
}

const account = createBankAccount(1000);
console.log(account.deposit(500));   // 1500
console.log(account.withdraw(300)); // 1200
console.log(account.balance);       // ❌ undefined (private variable)
Enter fullscreen mode Exit fullscreen mode

πŸ‘‰ Here, balance remains private β€” only accessible via closure functions.

  1. Function Currying

Closures make currying possible (breaking a function into multiple smaller functions).

function multiply(a) {
  return function(b) {
    return a * b;
  };
}

const double = multiply(2);
console.log(double(5)); // 10

const triple = multiply(3);
console.log(triple(5)); // 15

Enter fullscreen mode Exit fullscreen mode
  1. Event Listeners

Closures help preserve variables inside event listeners.

function setupButton() {
  let count = 0;

  document.getElementById("myBtn").addEventListener("click", function() {
    count++;
    console.log("Button clicked " + count + " times");
  });
}

setupButton();
Enter fullscreen mode Exit fullscreen mode

βœ… Advantages of Closures

  • Data Privacy: Protects variables from being accessed directly.
  • Stateful Functions: Functions can maintain state between executions.
  • Code Reusability: Helps create modular, reusable functions.
  • Useful in Asynchronous Code: Great for callbacks, promises, and event handling.

❌ Disadvantages of Closures

  • Memory Usage: Variables stay in memory longer than necessary, leading to higher memory consumption.
  • Hard to Debug: Tracing scope chains inside closures can be confusing.
  • Overuse Can Hurt Performance: If closures are created inside loops or used unnecessarily, they can slow down performance.

πŸš€ Conclusion

  • Closures are a powerful concept in JavaScript that allow you to:
  • Maintain state
  • Hide implementation details
  • Build reusable code

While they provide data privacy and are essential for asynchronous programming, developers should also be aware of the memory and debugging challenges.

πŸ‘‰ If you’re aiming to become a pro JavaScript developer, mastering closures is a must.

😊 Please follow me for more such content...

πŸš€ Rohit Singh πŸš€ – Medium

Read writing from πŸš€ Rohit Singh πŸš€ on Medium. Full-stack developer with 6+ years in Angular, Node.js & AWS. Sharing tips, best practices & real-world lessons from building scalable apps.

favicon medium.com

Top comments (0)