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

87

u/Mydrax May 28 '19

Closures are one of the most frequently misunderstood or barely ever undstood concept by beginner Javascript programmers. I personally believe that you will have a lot of "Oh, I see!" moments after you fully understand it. You will be capable of understanding certain things that previously didn't make sense to you because I assure you 100% that you've been using closures without even knowing it!

If you do not understand closures, please read this article, it gives you good understanding of what a normal function is and how it's execution takes place, then explains to you what a closure is. It's big but it will without doubt be an efficient use of time.

23

u/[deleted] May 28 '19

of "Oh, I see!" moments

I understand closure but had very few of these so far

15

u/Mydrax May 28 '19

Well, 2 really awesome use cases of closures I could name off the top of my head are:

  1. When you create function factories, where the outer function can be used to create functions that have similar concerns.

  2. The module pattern, that can be used to create private functions in javascript (where you return a set of functions whose logic is encapsulated).

2

u/turntopage294 May 28 '19

I'd been using 2 without knowing about closures, actually, for a time; I had an 'Oh, I see' moment after investigating when because closures love vaguely familiar

2

u/ScientificBeastMode strongly typed comments May 28 '19

Object factories are cool, and even class factories!

0

u/Memorytoco May 28 '19

just when use setTimeout and pass something like ( ) => {this.dosomething()} in some objects' method. or Array.forEach((entry) =>{ this.something()}).

1

u/Existential_Owl Web Developer May 29 '19

Closure can be used as a form of run-time memory.

That was a huge eye-opener for me.

1

u/thisisafullsentence May 28 '19

Could I roughly boil that article down to: closures a) have access to outside variables, but restrict inside variables and b) provide a new `this` context?

2

u/8lbIceBag May 29 '19

If you're using this in a closure I feel for most cases you're doing it wrong

1

u/thisisafullsentence May 29 '19

I generally agree in terms of code style, but many beginners wonder why `this` keeps changing and that's usually a result of a closure. The most typical solution of course is an arrow function but that syntax is an ES6 luxury.

1

u/[deleted] May 28 '19

Woah.

This article is awesome! I thought I understood what closures were but totally misunderstood the meaning.

Thanks!