Understanding JavaScript Closures with Simple Examples

Javascript

Closures are one of the most powerful and misunderstood concepts in JavaScript. Whether you’re preparing for an interview or building complex web apps, understanding closures is essential. Let’s break it down in the simplest way possible 👇

🔹 What is a Closure?

A closure is created when a function remembers variables from its parent scope even after the parent function has finished executing.

function outer() {
let name = 'Lokesh'; // variable in outer scope

function inner() {
console.log('Hello ' + name); // inner can access outer variable
}

return inner;
}

const greet = outer();
greet(); // Output: Hello Lokesh

✅ Even though outer() has finished running, inner() still remembers the variable name. This is called a closure.

🔹 How Closures Work (Step by Step)

  1. A function is defined inside another function.
  2. The inner function accesses variables from the outer function.
  3. The outer function returns the inner function.
  4. Even after the outer function is done, the inner function “remembers” those variables.

🔹 Real-Life Example: Counter Function

function counter() {
let count = 0;
return function() {
count++;
console.log('Current count:', count);
};
}

const increment = counter();
increment(); // Current count: 1
increment(); // Current count: 2
increment(); // Current count: 3

👉 The variable count is private and can’t be accessed directly. Only the returned function can modify it. This is a perfect example of data encapsulation using closures.

🔹 Why Are Closures Important?

  • They help create private variables
  • Used in event handlers and callbacks
  • Essential for module patterns and React hooks
  • Common in interview questions

🔹 Common Mistake with Closures

for (var i = 1; i <= 3; i++) {
setTimeout(() => console.log(i), 1000);
}

❌ Output: 4 4 4

Because var is function-scoped, all callbacks share the same i. To fix this, use let (block-scoped):

for (let i = 1; i <= 3; i++) {
setTimeout(() => console.log(i), 1000);
}

✅ Output: 1 2 3

🔹 Practical Example: Custom Event Handler

function createClickHandler(buttonName) {
return function() {
console.log(buttonName + ' clicked!');
};
}

const saveHandler = createClickHandler('Save');
saveHandler(); // Output: Save clicked!

This is exactly how closures help store specific data for different functions in your app.

🔹 Closure Interview Question

function makeAdder(x) {
return function(y) {
return x + y;
};
}

const add5 = makeAdder(5);
console.log(add5(10)); // Output: 15

Here, x is remembered by the inner function — even after makeAdder() has finished.

🔹 Summary

  • Closures allow inner functions to access variables from the outer scope.
  • They enable private variables and data encapsulation.
  • Used in advanced JS concepts like modules, hooks, and async callbacks.

💡 Tip:

Closures are not just for theory — they make your code clean, secure, and modular. Practice creating your own closure-based functions for better understanding.

📚 FAQ

Q1: Why are closures used in JavaScript?

Closures are used to retain access to variables after the parent function has executed — useful for private data and callbacks.

Q2: What is the difference between scope and closure?

Scope defines where a variable can be accessed; closure is when a function retains access to that scope after it’s gone.

Q3: Are closures used in React?

Yes, closures are used in React hooks like useState and useEffect to remember state and props across renders.

Next Lesson:

In the next blog, we’ll explore JavaScript Hoisting (var, let, const) — a crucial concept to understand how JavaScript actually executes your code.

Keep coding and keep growing 🚀

Share:

Understanding JavaScript Closures with Simple Examples

JavaScript closures allow functions to remember variables from their parent scope even after the parent function has finished. Let’s explore closures with simple and real-life examples.

JavaScript Promises Explained with Real-Life Examples

Understand JavaScript Promises with real-world examples. Learn how to use .then(), .catch(), and async/await for handling asynchronous operations effectively.

Master JavaScript Variables and Data Types | var, let, const Explained with Examples

Understand JavaScript variables and data types in a beginner-friendly way. Learn the difference between var, let, and const, and explore primitive and non-primitive data types with real examples.

Master JavaScript Conditional Statements (if, else, switch) with Examples

Understand JavaScript conditional statements and control program flow using if, else, and switch. Learn with examples and practical coding tips for beginners.

Understanding Variables and Data Types in JavaScript

Learn about JavaScript variables and data types — the foundation of every program. Understand var, let, const, and explore primitive and non-primitive data types with real-world examples.

What is JavaScript and Why Is It Important?

JavaScript is a powerful programming language that brings interactivity and life to web pages. It is one of the most essential skills for any web developer.