DEV Community

Cover image for πŸ”’ JavaScript Closures: The Ultimate Guide with Examples
ROHIT SINGH
ROHIT SINGH

Posted on

πŸ”’ JavaScript Closures: The Ultimate Guide with Examples

JavaScript is one of the most popular programming languages, and one of its most powerful yet sometimes confusing concepts is the Closure.
If you’ve ever wondered how JavaScript remembers variables even after a function has executed, the answer lies in closures.

In this blog, we’ll break down closures in simple terms, explore real-life examples, discuss their advantages and disadvantages, and show you why they are important for modern JavaScript development.

πŸ“Œ What is a Closure in JavaScript?

A closure is created when a function "remembers" the variables from its lexical scope even after that function is executed outside its original scope.

πŸ‘‰ In simple words:
Closures allow functions to access variables from an outer function, even after the outer function has finished execution.

πŸ§‘β€πŸ’» Example 1: Basic Closure

function outerFunction() {
  let counter = 0;

  function innerFunction() {
    counter++;
    return counter;
  }

  return innerFunction;
}

const increment = outerFunction();

console.log(increment()); // 1
console.log(increment()); // 2
console.log(increment()); // 3

Enter fullscreen mode Exit fullscreen mode

βœ… Here, innerFunction remembers the variable counter even though outerFunction has already finished execution. That’s closure in action.

πŸ“Œ Why Do We Need Closures?

Closures are useful in many scenarios:

Data Privacy (Encapsulation): Keep variables private.

State Management: Remember values without using global variables.

Callbacks & Event Handlers: Used heavily in asynchronous code.

Functional Programming: Enable currying and partial application.

πŸ§‘β€πŸ’» Example 2: Data Privacy with Closures

function createBankAccount(initialBalance) {
  let balance = initialBalance;

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

const account = createBankAccount(1000);

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

βœ… balance is private and can’t be accessed directly from outside. This is a real-life use of closures.

πŸ“Œ Advantages of Closures

βœ” Encapsulation β†’ Protects variables from being accessed globally.
βœ” Data Persistence β†’ Remembers state between function calls.
βœ” Asynchronous Support β†’ Useful in callbacks, timers, promises, etc.
βœ” Clean Code β†’ Encourages functional programming practices.

πŸ“Œ Disadvantages of Closures

❌ Memory Usage β†’ Variables captured by closures are not garbage collected until the function is no longer used.
❌ Complexity β†’ Can be confusing for beginners.
❌ Debugging Issues β†’ Hard to trace when many closures are nested.

πŸ§‘β€πŸ’» Example 3: Closure in Asynchronous Code

function delayedMessage(message, delay) {
  setTimeout(function() {
    console.log("Message: " + message);
  }, delay);
}

delayedMessage("Hello, Closure!", 2000); 
// Prints after 2 seconds: Message: Hello, Closure!

Enter fullscreen mode Exit fullscreen mode

βœ… Even though delayedMessage is finished, the inner function still remembers message.

🎯 Real-World Applications of Closures

Debouncing & Throttling in JavaScript

Implementing private variables in OOP

Custom hooks in React.js

Event handling in DOM

Module patterns for reusable code

βœ… Conclusion

Closures are one of the most powerful features of JavaScript. They allow you to write more modular, secure, and maintainable code. While they may seem tricky at first, mastering closures will take your JavaScript skills to the next level.

πŸ‘‰ Remember:
A closure = function + lexical environment.

πŸš€ 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)