DEV Community

Cover image for Understanding Closures in JavaScript

Understanding Closures in JavaScript

Avwerosuoghene Darhare-Igben on August 13, 2023

Closures might seem puzzling at first, but they're actually a powerful tool in JavaScript. Think of them as hidden treasures that help make JavaScr...
Collapse
 
vip3r011 profile image
vip3r011

Correct me if I'm wrong, but your last example is const , u cant reassign that to null

Collapse
 
avwerosuoghene profile image
Avwerosuoghene Darhare-Igben

Thanks for spotting that out. You are absolutely right, and that was an oversight from my end.
We can either define the expensiveClosure variable using the let keyword, or create a function inside our closure that releases resources when we no longer need them.

Collapse
 
manvendrask profile image
Manvendra Singh

That is why we use TypeScript, but here your editor should have caught it.

Thread Thread
 
avwerosuoghene profile image
Avwerosuoghene Darhare-Igben

Yeah, I used javascript for that particular snippet that's why.
More reason why typescript is essential.

Collapse
 
elayomohammed profile image
elayomohammed

Quite a good share, thanks 😊

Collapse
 
tallangroberg profile image
Tallan Groberg

Very well explained. Thanks for sharing.

Collapse
 
avwerosuoghene profile image
Avwerosuoghene Darhare-Igben

I'm pleased that the explanation was clear and beneficial to you.

Collapse
 
robinamirbahar profile image
Robina

Nice Work

Collapse
 
avwerosuoghene profile image
Avwerosuoghene Darhare-Igben

I'm glad you enjoyed the article.🙂

Collapse
 
sllayan profile image
Shayan • Edited

One of the best explanations about closure. good job.

Collapse
 
pardeepr08 profile image
pardeepr08

Awesome read