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?

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.

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".

12

u/lostPixels May 28 '19

In my experience working on a codebase with 10,000+ LOC, we never use closures. Every method is generally treated as atomic, where every call just accepts arguments are predictably returns results. Closures are cool but in my opinion can be confusing enough that they will cause some less JS focused developers a lot of issues debugging.

9

u/theycallmeepoch May 28 '19

Yes, I feel like a pure functional programming approach helps minimize the need.

It seems like it was good for making your own getter and setter functions but those are built into JS now...

1

u/[deleted] May 31 '19

I feel exactly the opposite. In a purely functional codebase, you're almost definitely going to be using curried functions and partial application, which only exist in Javascript because of closure.

1

u/ScientificBeastMode strongly typed comments May 28 '19

I tend to agree with you there. Predictability is important for testing functions, and closures add complexity.

But as far as function dependencies go, closures provide a better way to inject dependencies than simply storing dependencies in some outer scope that other parts of your code can have access to and possibly mutate.

At least you know that the only functions that have access to that dependency are the ones that were returned from that closure. But it’s not something I would want to do very often.

1

u/lostPixels May 28 '19

I agree with you totally. These days, my team usually will be working with React and we stick with pure functional programming as much as possible. However in the past I have had times where a closure would work, but in that case I actually would opt to use the new keyword and made instances of a Thing that all have internal scope, but could be observed and interacted with. It's really just a question of preference and using the right tool for the job.

1

u/ScientificBeastMode strongly typed comments May 28 '19

That’s probably the better option, both for transparency and for memory safety. But I’m definitely on board the functional programming train nowadays, especially with React.

1

u/fallen_atreus May 28 '19

When we talk about atomic functions that produce always the same kind of output with the given output, are we not talking about the functional programming paradigm?

1

u/[deleted] May 31 '19

You don't use partial application or currying?

0

u/FormerGameDev May 28 '19

so, you never pass an anonymous function to array.map, filter, etc ?

3

u/el_graveto May 28 '19 edited May 28 '19

Lets say you are making a function that stores properties of pen, like function pen, and properties color, shape, lvl of ink, those properties only exist inside of your function. That is good because you avoid conflict with other parts of your code, but if you need to call those properties or change them? You could do it easily by nesting a function inside your function pen that do whatever you want with those properties, those properties are inside that child function scope but out of the rest of the code scope. You can even call that nested function as argument in another function, it create many possibilities and once you get the hang of it you spend less time coding and have a cleaner code, less prone to bugs, also since those properties (or variables, methods,..) are inside of the function scope you avoid memory leaks.

3

u/theycallmeepoch May 28 '19

What is the advantage to using a function instead of declaring the pencil as an object with its own properties and methods?

4

u/circlebust May 28 '19

You use a function to create such an object if you want an object (ES6 Classes are just syntactic sugar over functions), but the other way around doesn't work if you ever want more than one single pencil in your program.

1

u/mkymonkey May 29 '19

What happened to pen?

2

u/el_graveto May 29 '19

I realized that i wrote pencil and pen as the same thing so i changed to not get confusing

1

u/[deleted] May 31 '19

The pen factory got used to create a pencil by leveraging closure?

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.

5

u/kamenjan May 28 '19

I think he meant that your dev time is normal if you understand closures :) You know right away when to use arrow function and when not to, so you avoid frequent and pointless code refactoring on account of not understanding closures :)

11

u/[deleted] May 28 '19

I'd argue arrow functions have nothing to do with closures. Scope and closure are not synonymous.

6

u/[deleted] May 28 '19

If you are a React developer, you are leveraging closures on every single component render even if you're not realizing it.

1

u/8lbIceBag May 29 '19

It doesn't really. Maybe because everything is private and you don't have to use this everywhere or program as defensively?

In my experience, if you're someone building off or extending a library, it will slow you down. It sucks to extend a library or framework that uses closures because you don't have access to internals. Also closures are slower and more resource intensive (execution wise) if there's many instances.

Great for singletons or for your own libraries that no one has to extend though