Closure in JavaScript: Examples and Practical Use Cases

JavaScript closures are one of the most important concepts every JavaScript developer should understand. Whether you are preparing for a technical interview, building web applications, or learning advanced JavaScript, understanding closures can help you write cleaner, more reusable, and maintainable code.

Closures are frequently used in real-world JavaScript applications, especially in event handlers, callbacks, factory functions, and asynchronous programming. They also play an important role in React development.

In this guide, we will explain what closure is in JavaScript, how it works, why it is useful, and where developers use it, with practical examples you can try yourself.

1. What Is Closure in JavaScript?

A closure in JavaScript is a function that remembers and can access variables from its outer scope, even after the outer function has finished executing.

In simple words, a closure allows an inner function to remember variables defined in its surrounding environment.

Let’s understand this with a basic example.

function outer() {
  let message = "Hello JavaScript";

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

  return inner;
}

const myFunction = outer();

myFunction(); // Hello JavaScriptCode language: JavaScript (javascript)

How Does This Example Work?

  1. The outer() function creates a variable named message.
  2. Inside outer(), another function named inner() is declared.
  3. The inner() function accesses the message variable from its outer scope.
  4. The outer() function returns the inner() function.
  5. Even after outer() finishes executing, inner() can still access message.

This behavior is called closure.

The important point is that JavaScript does not automatically remove all variables associated with an outer function when that function returns. Variables that are still reachable through a closure can remain available.

2. Understanding Lexical Scope in JavaScript

Before learning closures in depth, it is important to understand lexical scope.

Lexical scope means that the location where a variable or function is written determines which variables it can access.

JavaScript uses lexical scoping, meaning an inner function can access variables declared in its surrounding scopes.

Example:

let globalVariable = "Global";

function parent() {
  let parentVariable = "Parent";

  function child() {
    let childVariable = "Child";

    console.log(globalVariable);
    console.log(parentVariable);
    console.log(childVariable);
  }

  child();
}

parent();Code language: JavaScript (javascript)

Output:

Global
Parent
ChildCode language: PHP (php)

The child() function can access variables from its own scope, its parent function, and the global scope.

However, the parent function cannot directly access variables declared inside the child function.

Closures are closely connected to lexical scope because they preserve access to the surrounding lexical environment.

3. How Closures Work in JavaScript

A common question is: What happens when the outer function finishes executing?

Normally, local variables are no longer needed after a function completes. However, when a returned inner function references those variables, JavaScript keeps the necessary environment available.

Consider this example:

function createCounter() {
  let count = 0;

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

const counter = createCounter();

console.log(counter()); // 1
console.log(counter()); // 2
console.log(counter()); // 3Code language: JavaScript (javascript)

Here, the variable count is declared inside createCounter().

When createCounter() executes, it returns an anonymous function.

Even after createCounter() finishes, the returned function remembers the count variable.

Every time we call counter(), the same variable gets updated.

This is one of the simplest and most frequently asked closure examples in JavaScript interviews.

4. Closures and Data Encapsulation

One of the most useful applications of closures is data encapsulation.

Data encapsulation means restricting direct access to internal variables and providing controlled methods to interact with them.

Example:

function createBankAccount(initialBalance) {
  let balance = initialBalance;

  return {
    deposit(amount) {
      if (amount > 0) {
        balance += amount;
      }

      return balance;
    },

    withdraw(amount) {
      if (amount > 0 && amount <= balance) {
        balance -= amount;
      }

      return balance;
    },

    getBalance() {
      return balance;
    }
  };
}

const account = createBankAccount(1000);

console.log(account.deposit(500));  // 1500
console.log(account.withdraw(200)); // 1300
console.log(account.getBalance());  // 1300Code language: JavaScript (javascript)

In this example, the balance variable cannot be accessed directly using account.balance.

Instead, it can only be accessed or modified through the methods returned by createBankAccount().

This approach improves code organization and prevents accidental modification of internal state.

Important: Closures provide encapsulation, but they should not be treated as a security boundary for storing passwords or other sensitive credentials in client-side JavaScript. Secure authentication requires appropriate server-side controls.

5. Closures in Factory Functions

Factory functions are functions that create and return objects or other functions.

Closures are useful in factory functions because they allow each generated function to maintain its own information.

Example:

function createMultiplier(multiplier) {
  return function (number) {
    return number * multiplier;
  };
}

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

console.log(double(5)); // 10
console.log(triple(5)); // 15Code language: JavaScript (javascript)

Here, createMultiplier(2) creates a function that remembers the value 2.

Similarly, createMultiplier(3) creates another function that remembers 3.

Both functions use closures, but each has its own captured environment.

This pattern is useful when you need configurable and reusable functions.

6. Closures in Event Handlers

Closures are also commonly used in browser event handling.

Consider a button that counts how many times a user clicks it.

function setupButton() {
  let clickCount = 0;

  const button = document.getElementById("myButton");
  if (!button) return;

  function handleClick() {
    clickCount++;
    console.log(`Clicked ${clickCount} times`);
  }

  button.addEventListener("click", handleClick);
  return () => button.removeEventListener("click", handleClick);
}

const cleanupButton = setupButton();Code language: JavaScript (javascript)

Run this snippet after rendering a button with the ID myButton. Every time the button is clicked, the event handler updates clickCount.

Although setupButton() has finished executing, the event handler retains access to its variable.

This makes closures useful for maintaining local state in interactive web applications.

Call cleanupButton?.() when the UI is removed. The cleanup function remembers the original handler so it can remove that exact listener.

7. Closures in Asynchronous JavaScript

Closures are important when working with asynchronous operations, including timers, promises, and callbacks.

Example:

function delayedGreeting(name) {
  setTimeout(function () {
    console.log(`Hello, ${name}`);
  }, 2000);
}

delayedGreeting("John");Code language: JavaScript (javascript)

After approximately two seconds, the output will be:

Hello, John

The setTimeout() callback remembers the name variable even though delayedGreeting() has already returned.

This happens because the callback forms a closure over its surrounding scope.

Understanding this behavior is especially helpful when working with asynchronous APIs and JavaScript application development.

8. Common Closure Mistake: var Inside a Loop

One classic JavaScript interview question involves closures inside loops.

Consider the following code:

for (var i = 0; i < 3; i++) {
  setTimeout(function () {
    console.log(i);
  }, 1000);
}Code language: JavaScript (javascript)

What will be printed?

3
3
3

Many beginners expect the output to be 0, 1, and 2.

However, var is function-scoped, not block-scoped. All three callbacks reference the same i variable.

By the time the timer callbacks execute, the loop has finished and i equals 3.

Solution: Use let Instead of var

for (let i = 0; i < 3; i++) {
  setTimeout(function () {
    console.log(i);
  }, 1000);
}Code language: JavaScript (javascript)

Output:

0
1
2

With let, JavaScript creates a new binding for each loop iteration.

Each callback therefore reads from a separate binding. Closures capture bindings, so later changes to a shared binding are visible to every function that reads it.

This example demonstrates why understanding lexical scope and closure behavior is important when writing asynchronous JavaScript.

9. Closures in React Applications

Closures also play an important role in React applications.

React function components use JavaScript closures to access variables defined during rendering.

Consider a simple component:

import { useState } from "react";

function Counter() {
  const [count, setCount] = useState(0);

  function handleClick() {
    setCount(previousCount => previousCount + 1);
  }

  return (
    <button onClick={handleClick}>
      Count: {count}
    </button>
  );
}

export default Counter;Code language: JavaScript (javascript)

In this example, handleClick() is defined inside the Counter component.

The function has access to variables in the component’s scope through JavaScript’s lexical scoping and closure behavior.

React also introduces an important concept called a stale closure.

A stale closure occurs when a callback continues using values captured during an earlier render instead of the values from a newer render.

For example, a timer callback created by an effect with an empty dependency array may keep reading the initial state value.

Using functional state updates, correct effect dependencies, or refs where appropriate can help avoid stale closure problems.

This makes closures an important topic for both JavaScript and React interviews.

10. Advantages of Closures in JavaScript

Closures offer several benefits when used correctly.

Data encapsulation: Closures help keep implementation details private and expose controlled interfaces.

State preservation: They allow a function to retain access to variables across multiple calls.

Reusable functions: Closures support function factories that produce customized behavior.

Callback support: They allow asynchronous callbacks and event handlers to access variables from the surrounding scope.

Better organization: Closures can reduce unnecessary global variables and help organize related behavior.

However, closures do not automatically improve performance or reduce memory usage. Their value depends on how they are used.

11. Disadvantages and Potential Problems with Closures

Although closures are useful, developers should understand their limitations.

Memory Retention

A closure can keep referenced objects reachable longer than expected.

If a callback retains large objects, those objects may remain in memory while the callback is still reachable.

Debugging Complexity

Nested functions and captured variables can sometimes make code harder to understand.

Stale Values

In asynchronous applications or React components, functions may reference values captured from earlier executions.

Unnecessary Complexity

Using closures for every problem can make code harder to maintain.

The best approach is to use closures where they provide clear benefits, such as encapsulation, reusable configuration, or callback state.

12. JavaScript Closure Interview Questions and Answers

Q1. What is closure in JavaScript?

A closure is a function that remembers and can access variables from its outer lexical scope, even after the outer function has finished executing.

Q2. Why are closures used?

Closures are used for data encapsulation, maintaining state, creating reusable functions, and handling asynchronous callbacks.

Q3. Does every JavaScript function form a closure?

JavaScript functions are created with access to their lexical environment. When a function uses variables from its surrounding scope, that behavior demonstrates closure.

Q4. What is the difference between scope and closure?

Scope determines where variables can be accessed.

A closure allows a function to retain access to its surrounding lexical environment when the function is used elsewhere.

Q5. Can closures cause memory leaks?

Closures can contribute to unnecessary memory retention when long-lived callbacks keep large objects reachable. However, closures themselves do not automatically cause memory leaks.

Q6. What is a real-world example of closure?

A counter function that maintains its value between calls is a common example. Event handlers, function factories, and private module state are other practical use cases.

Q7. What is a stale closure in React?

A stale closure occurs when a function continues referencing values captured during an earlier render, even after the component has rendered with updated values.

13. Best Practices for Using Closures

To use closures effectively in production applications, keep these practices in mind:

  1. Use const and let instead of var when appropriate to avoid confusing scope behavior.
  2. Keep closure logic simple and readable.
  3. Avoid capturing large objects unnecessarily in long-lived callbacks.
  4. Remove event listeners and clean up timers when they are no longer required.
  5. Use closures to encapsulate state when a simple object or class would be unnecessarily complex.
  6. In React, understand effect dependencies and functional state updates to prevent stale closures.
  7. Test callback behavior carefully, particularly when multiple functions share the same captured variable.

Following these practices makes JavaScript code more predictable and easier to maintain.

14. Conclusion

Closures are a fundamental part of JavaScript and an essential concept for developers working with modern web applications.

The simplest way to remember a closure is:

A closure is a function that remembers variables from its outer scope, even after the outer function has finished executing.

From maintaining counters to creating factory functions, handling events, and managing asynchronous callbacks, closures appear throughout JavaScript development.

Understanding closures will also improve your knowledge of lexical scope, higher-order functions, React hooks, and asynchronous programming.

The best way to master closures is to practice writing small examples and understand which variables each function captures.

For more tutorials on JavaScript, React, Next.js, and modern web development, explore DevCraft Labs.

Further Reading

Leave a Reply

Your email address will not be published. Required fields are marked *