Closure in JavaScript.
What is Closure in JavaScript.
What is a Closure in JavaScript? (Very Simple Explanation)
A closure is a function that remembers variables defined around it—even if that function is called later.
Think of closures like this:
When a function is created, it "remembers" the environment where it was born. A closure is exactly that—it's that memory.
Example: Step by Step
function sayHello() {
const name = "Anna";
function greet() {
console.log("Hello, " + name);
}
return greet;
}
What's happening here?
- We have a
sayHellofunction. - Inside it, there's a variable
name = "Anna". - Another inner function
greet()is defined inside. - We return the
greetfunction.
How to Use It
const greeting = sayHello(); // greeting is now the same as the greet function
greeting(); // "Hello, Anna"
This is where the magic of closures happens:
Even though the sayHello function has finished executing, the inner name = "Anna" value is still remembered because the greet() function is a closure and retains the environment where it was created.
Why Are Closures Useful?
Closures are a powerful tool. They help:
Keep Data Private
function createCounter() {
let count = 0;
return function () {
count++;
return count;
};
}
const counter = createCounter();
console.log(counter()); // 1
console.log(counter()); // 2
console.log(counter()); // 3
Here, the count variable is inaccessible from outside, but the inner function (via the closure) can see and modify it.
Remember Variables for Later Use
function delayedMessage() {
const message = "This is a closure!";
setTimeout(function () {
console.log(message); // The closure retains the message
}, 2000);
}
delayedMessage();
Recap: The Key Idea
A closure is a function that remembers variables around it, even after the outer function where those variables were defined has finished executing.
- 0
- 40