r/javascript • • May 28 '19

What are some JavaScript things beginners don't know?

333 Upvotes

383 comments sorted by

View all comments

152

u/[deleted] May 28 '19

Closure is a concept I see lots of beginners struggle with. You can massively speed up dev time once you grasp how it works in JS.

23

u/priceLbear May 28 '19

A few weeks ago I spent some time learning about closure and I understand the concept. How exactly does it speed up dev time though? Do you use it often? If yes, could you describe some use cases I obviously fail to see?

8

u/superluminary May 28 '19

JavaScript treats functions as data. A function is a datatype, just like any other object. This means you can pass it around from place to place just as you would pass a string or a number.

What closure gives you is a stable environment to do this. When you create a function, it gains a closure scope that contains all the variables that the function could see when it was defined. These variables are still available no matter when and how you run your function in the future.

Some example use cases are:

Event handlers. Create them now, and have your code execute them later in another context. They still work.

ES6 modules. All those variables you declare in your module live in the function closure. Import them later, they still work.

There are many others. It's core to the language.