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.

12

u/razorsyntax May 28 '19

I never understood why we don’t call closures “scope”? What’s the difference between closures and scope in, say, C++ or Java?

20

u/senocular May 28 '19

Scope is where values are defined. Closures are functions which reference one or more scopes. They're related but not the same thing

1

u/8lbIceBag May 29 '19

Also in other languages you can usually bypass scope via reflection if you really need to. Js closures though, good luck as far as u know. Usually gotta copy the entire closure by text then edit the raw string then eval if you need to hook something or edit a private variable

1

u/[deleted] Jun 25 '19

Closures do not "reference" one or more scopes.

Closures are the combinations of a function and its lexical scope.

1

u/senocular Jun 25 '19

That "combination" being a function and and a reference to the scope chain that represents the lexical scope. If two closures are defined in the same scope, the reference to their scope chain will be the same.

→ More replies (2)

5

u/eatsomeonion May 28 '19

Closure is part of the function scope property

5

u/Candyvanmanstan May 28 '19

Because closure and scope isn't the same in javascript either. A closure can have access to three scopes. It's own scope, an outer functions scope, and global variables.

2

u/ScientificBeastMode strongly typed comments May 28 '19

You can also take a function as an argument (or from a reference in an outer scope), and apply it inside the current function’s scope, which is how classes are “extended.”

→ More replies (1)