Closures in JS.

Rajan Lagah
2 min readNov 14, 2021

--

When you define a function in JS it will be bundled with all the variables that are being used inside that function.

Example

function s() {
let a = 1
function b() {
console.log(a)
}
b()
}
s()

Now function b is aware of value a. If we run this in browser with dubugger at console.log(a) we can check the memory allocation.

We can see variable a is saved under Closure.

function s() {
let a = 1
function b() {
let b = 2;
function c() {
console.log(a,b)
}
c()
}
b()
}
s()

For above function we can see

We have 2 different clousures for 2 different function ‘b’ and ‘s’.

Making variables private

One use case of closure is ristricting access of variables.

function a(){
var count = 0
return function counter(){
count++
console.log(count)
}
}
const counter = a()
counter()
counter()
counter()
// o/p
// 1
// 2
// 3

Now count variable is not accessible outside the a function.

Memoization

Other benifit is it will memorize the value of variables and need not to calculate again and again.

function a(){
var count = 0
function someWork(){
console.log("HEAVY WORK")
count = 1000*999
}
someWork()
return function counter(){
count++
console.log(count)
}
}
const counter = a()
counter()
counter()

If we check the output we will see that HEAVY WORK is logged just once and the counter output is 999001 and 999002 .

Now this show function memorizes the value of count updated by function someWork both time when function counter is called.

Drawback

Drawback of closure is the variables are not garbage collected. Like variable count in above code will not be garbage collected hence the code will take more memory.

Let me know if we can improve this by adding/removing something.

--

--

Rajan Lagah
Rajan Lagah

Written by Rajan Lagah

React expert and Deep learning beginner.

No responses yet