DEV Community

Cover image for What is a "Closure" in JavaScript?

What is a "Closure" in JavaScript?

Emmy | Pixi on July 24, 2020

What is a "closure"? A closure is the combination of a function enclosed with references to its surrounding state (lexical environment)....
Collapse
 
greedybrain profile image
Naya Willis

That insideoutaide then outside we inside gave me a headache. Im going to bed lol. Jk, great stuff. Thanks for helping me understand it a little more as well. 😁

Collapse
 
thecodepixi profile image
Emmy | Pixi

Haha sorry! I thought the naming was kinda funny, but I can see how it might be confusing 🙈

Collapse
 
greedybrain profile image
Naya Willis

Lol I was just kidding.

Collapse
 
mohsenalyafei profile image
Mohsen Alyafei

Thank you for the article.
I had always been using the concept, but never called it a "closure". I have it in my mind as a "function wrapper". It allows all my inner wrapped functions (and at times do have a lot of them) to use all the common variables I have already declared in the main outer function without having to pass them individually to each function and declare them again.

Collapse
 
bionboy profile image
Luke Floden

Are multi-level closures classified as something else or just call something like "nested closures"?

Collapse
 
thecodepixi profile image
Emmy | Pixi

I'm honestly not sure 🤔 that might get more into specific scope than closure itself. But, for instance, let's say in my "inside outside" example, there was a local scope variable inside of inside, that would be inside the "closure" created by the inside function. But I'm not sure if there's any kind of special term for that in terms of closures.

Collapse
 
sandricoprovo profile image
Sandrico Provo

Closures have always broken my brain a little bit 😅, but this explanation makes it quite clear! Thank you for sharing 😄.

Collapse
 
thecodepixi profile image
Emmy | Pixi

Thank you Sandrico! I'm so glad this helped clear things up for you 🤗

Collapse
 
ianwijma profile image
Ian Wijma

I aways thought this concept was called a Factory pattern.

Collapse
 
thecodepixi profile image
Emmy | Pixi

I've never heard that term before 🤔 I guess I'll have to look it up

Collapse
 
amlana24 profile image
amlan

Great explanation..Closures always confuse me..