DEV Community

What are closures?

wrongbyte on September 29, 2022

The concept of closure is important when it comes to understanding how languages such as Javascript work - and how scopes, lifetimes and references...
Collapse
 
crowdozer profile image
crowdozer • Edited

Something to add: you can create new scopes anywhere you want, provided the compiler doesn't think you're trying to initialize an object. A function body isn't necessary.


const x = 'foo'
console.log(x) // 'foo'

{
  const x = 'bar'
  console.log(x) // 'bar'
}

console.log(x) // 'foo'
Enter fullscreen mode Exit fullscreen mode

Though, doing that looks ugly and probably isn't ideal. An example of a valid use case is switch statements, it allows you to isolate each case into its own local scope.

Collapse
 
wrongbyte profile image
wrongbyte

You are right, this is also something interesting about scopes. Thanks for pointing out!

Collapse
 
wiseai profile image
Mahmoud Harmouch • Edited

In ReactJS, my first encounter with closures was in form of arrow functions:

closure

I was so confused at first, then i was like: wait a sec, it is just something that returns something that in return returns something. Aha! Know what i am sayin'?

Edit: For the sake of correctness, I think this statement is somewhat wrong:

there are several other use cases for closures - such as currying

Currying is the broader term, and closure is just a practice of it in programming.

Collapse
 
wrongbyte profile image
wrongbyte

Thanks for pointing out! I've updated the post 😆

Collapse
 
____marcell profile image
Marcell Cruz

Your posts are getting better and better every time, really good explanation and examples

Collapse
 
wrongbyte profile image
wrongbyte

Tnx, I'm really glad to help 😊

Collapse
 
daniloab profile image
Danilo Assis

nice post, congratz

Collapse
 
wrongbyte profile image
wrongbyte

Thanks 😊

Collapse
 
incrementis profile image
Akin C.

Hello wrongbyte,

Thank you for your article.
I read something about closures years ago.
Reading your article helped me refresh some of my knowledge about closures.

Collapse
 
wrongbyte profile image
wrongbyte

I'm glad I could help! 😄

Collapse
 
darkwiiplayer profile image
𒎏Wii 🏳️‍⚧️

Nice post. Closures are one of the most useful concepts to understand in languages that have them.

Collapse
 
wrongbyte profile image
wrongbyte

For sure! And they are very interesting