Closure in JavaScript.
What is Closure in JavaScript.
A closure is a function that remembers variables defined around it—even if that function is called later.
When a function is created, it "remembers" the environment where it was born. A closure is exactly that—it's that memory.
function sayHello() {
const name = "Anna";
function greet() {
console.log("Hello, " + name);
}
return greet;
}
What's happening here?
sayHello
function.name = "Anna"
.greet()
is defined inside.greet
function. 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.
Closures are a powerful tool. They help:
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.
function delayedMessage() {
const message = "This is a closure!";
setTimeout(function () {
console.log(message); // The closure retains the message
}, 2000);
}
delayedMessage();
A closure is a function that remembers variables around it, even after the outer function where those variables were defined has finished executing.