r/javascript • • May 28 '19

What are some JavaScript things beginners don't know?

333 Upvotes

383 comments sorted by

View all comments

Show parent comments

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?

18

u/[deleted] May 28 '19

The better you understand it the more efficient your architecture becomes and less time you spend debugging issues that involve global and local variables not being available to functions etc.

16

u/theycallmeepoch May 28 '19

I would really love to see some examples of this as it's not clear to me yet the benefits other than creating a nested function which has "private" variables. I'm not quite at Closures yet in "Secrets of the Javascript Ninja".

1

u/[deleted] May 31 '19

Partial application and currying are top uses for closure.

Let's say you're doing a fetch on an API to get users, you can configure the fetch call, get back a function preloaded with that configuration (with authentication or whatever you need to access the API), and then use that function when you want a user.

const factoryUserData = (baseUrl) => (config) => (username) => fetch(`${baseUrl}/${username}`, config)

const getUserData = factoryUserData('https://sweetap.io')({ /* configuration object */})

getUserData('ratchetboi420').then(funcToRunOnUserData)

getUserData('bigdaddy69').then(...)

Obviously, in a real application, you might put the arguments in a different order, and you might inject fetch as well, for testing and whatnot. But some form of this pattern is really useful.