WHAT IS CLOSURES IN JAVASCRIPT?
A closure is when a function remembers and has access to variables from its outer scope even after the outer function has finished executing.
Simple example
function outer() {
let name = "John";
function inner(){
console.log(name);
}
return inner;
}
const myFunction = outer();
myFunction();
Output:
John
why does this work?
Normally, you might think name should disappear after outer() finishes.
But inner() remembers the name variable.
outer()
|
|-- name = "John"
|
|-- inner()
|
|-- remembers "John"
That remembering ability is called a closure.
One more useful example
Closures are often used to create private variables:
function counter() {
let count = 0;
return function () {
count++;
console.log(count);
};
}
const myCounter = counter();
myCounter(); // 1
myCounter(); // 2
myCounter(); // 3
Even though counter() has already finished, the returned function still remembers count.
So:
Closure = A function + the variables from its surrounding environment that it remembers.
Top comments (0)