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

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.

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.