Closures in JavaScript
Bishnu Prasad Chowdhury
Posted on March 3, 2021
In JavaScript we can pack a function inside another function. When one function A is inside another function B then function A is called outer function while function A is called inner function and this phenomenon is called a closure.
In closure the inner function can have access to the outer function scope.
function B() {
let x = 7;
function A() {
console.log(x);
}
return A;
}
var c = B();
c();
>7
Closures are used to make private function or variables that has limited access. The outer function of a closure cannot access the inner function scope so it can be used to hide data.
Apart from this use closure do have drawbacks where as long as closure is running memory cannot be garbage collected resulting to memory leaks. This can be avoided by making them null force fully after the use.
Posted on March 3, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
November 29, 2024