Closures in JavaScript

Sanjana Human In Tech
1 min readOct 26, 2023

--

Function bundled along with its lexical scope is closure. JavaScript has a lexical scope environment. If a function needs to access a variable, it first goes to its local memory. When it does not find it there, it goes to the memory of its lexical parent. See the Below code, over here function y along with its lexical scope i.e. (function x) would be called a closure.

function x() {
var a = 7;
function y() {
console.log(a);
}
return y;
}
var z = x();
console.log(z); // value of z is entire code of function y.

In the above code, when y is returned, not only is the function returned but the entire closure (fun y + its lexical scope) is returned and put inside z. So when z is used somewhere else in the program, it still remembers var an inside x()

Thus, in simple words, we can say: A closure is a function that has access to its outer function scope even after the function has returned. Meaning, A closure can remember and access variables and arguments in reference of its outer function even after the function has returned.

Advantages of Closure: Module Design Pattern Currying Memoize Data hiding and encapsulation setTimeouts etc.

Disadvantages of Closure: Over consumption of memory Memory Leak, Freeze browser

--

--

Sanjana Human In Tech
Sanjana Human In Tech

Written by Sanjana Human In Tech

A React Native front-end enthusiast and dedicated development engineer, eager to expand knowledge on development techniques and collaborate with others.

No responses yet