Closures in JavaScript: What, How, and Why They Matter

K ManojK Manoj
4 min read

🔸 Introduction

Ever found yourself puzzled over how a function in JavaScript can remember variables long after its parent has finished executing? That, my friend, is the power of closures.

They're the secret sauce behind many elegant solutions and are fundamental to functional programming. Let's demystify closures and explore why they're such a big deal.

❓What Are Closures?

A closure is simply: A function that remembers the variables from its lexical scope, even when that function is executed outside that scope.

In simpler terms: A closure gives you access to an outer function’s variables from an inner function, even after the outer function has returned.

function outer() {
  let count = 0;

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

const counter = outer();
counter(); // 1
counter(); // 2
counter(); // 3

Even though outer() has already finished execution, the inner() function still has access to count. That’s a closure in action.

🩻 The Anatomy of a Closure

Every closure consists of three key components:

  1. The Function: The actual function code

  2. The Environment: Variables from the enclosing scope

  3. The Binding: The connection between the function and its environment

When a function is created, it captures references to the variables it needs from its surrounding scope. This captured environment travels with the function, creating a "closure" around it.

🛠️ How Do Closures Work Internally?

Closures rely on lexical scoping, which implies that the scope of a variable is determined by its position in the source code.

When you create a function, JavaScript doesn’t just store the function code — it also saves the surrounding variables in a lexical environment. This environment closes over the variables.

function greet(name) {
  return function message() {
    console.log(`Hello, ${name}!`);
  };
}

const sayHello = greet("Manoj");
sayHello(); // Hello, Manoj!

Even though greet() is long gone, message() still remembers name. The closure captures the variable, not just its value, meaning it’s a living reference — any change in the outer variable will reflect in the closure.

Behind the scenes:

  • Function is created with its lexical scope.

  • On calling greet(), the environment where name = "Manoj" is preserved.

  • The inner function retains access to this scope through a closure.

🎯 Why Should You Use Closures?

  1. Data Privacy
function encryptedCode() {
  let code = "2025";

  return {
    getCode: () => code,
    setCode: newCode => code = newCode
  };
}

const vault = encryptedCode();
console.log(vault.getCode()); // 2025
vault.setCode("2026");
console.log(vault.getCode()); // 2026

Closures provide a way to create private variables in languages that don't have built-in privacy mechanisms.

  1. Function Factories
function multiplier(factor) {
  return function(num) {
    return num * factor;
  };
}

const double = multiplier(6);
console.log(double(9)); // 54
  1. Callback Functions
function fetchData(callback) {
  const data = "Hello World!";
  setTimeout(() => {
    callback(data); // callback accesses data from outer scope
  }, 1000);
}

They're essential for maintaining context in callbacks and asynchronous operations.

🌎 Real-World Use Cases

React Hooks

If you use React, closures are the backbone of hooks like useState and useEffect. Ever wondered why a hook "remembers" the previous state? You guessed it — closures!

Debouncing & Throttling

Closures preserve timer IDs or counters for optimizing scroll and input events.

⛳️ Conclusion

Closures are one of the most powerful features in JavaScript. Once you understand how a function can “remember” variables from its birth environment, you unlock a whole new layer of capabilities.

Whether you’re building private variables, dynamic functions, or advanced async flows, closures give you the power to write cleaner, safer, and more modular code.

✍️ Missed My Last Blog?

https://kmanoj.hashnode.dev/lexical-environments-and-scope-chains

🔍 Discover how JavaScript scopes your variables and functions through lexical environments and the scope chain.

🤝 Connect with Me

If you enjoyed this blog and want to stay updated with more JavaScript insights, developer tips, and tech deep-dives — feel free to connect with me across platforms:

🔗 LinkedIn: Connect with me on LinkedIn

📝 Medium: Follow me on Medium

🌐 Hashnode: Check out my Hashnode blog

I appreciate your support and look forward to connecting with fellow devs, learners, and curious minds like you! 🚀

0
Subscribe to my newsletter

Read articles from K Manoj directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

K Manoj
K Manoj

Backend Web Developer | Security Enthusiast |