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/[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.

1

u/[deleted] Jun 25 '19

There is no reference to no scope, there's a context of execution. Saying that is a reference to a scope it makes it look like if there's like a list of of references to data structures, but I think this is the wrong way to paint it like a reference because if it was a reference to such thing I should be able to access its local state and I'm not aware of this possiiblity.

1

u/senocular Jun 26 '19

You can access it, using the debugger. In Chrome you can see each individual scope that is available and which variables they have access to (those which haven't been optimized away), just as you would any normal object logged to the console. They're treated very similar, so in that context, referring to them as references make sense.