Scope Chains, Closures, Hoisting, and Garbage Collection all have one thing in common: They’re often hand-waved away. How do closures actually work? When does Garbage Collection occur? What really IS the Scope Chain?
In this talk, we will discover it’s not black magic after all; No hand waving is required to explain these language features, in fact you’ve been using them all along without realising.
- var – lexical scoping
- let – block scoping
- const – block scoping
- JS does 2 pass parsing.
- First pass (hoisting) gives scope – variables get ‘hoisted’ up to the top of the function.
- This is where lots of confusing bugs begin. Google this if you aren’t comfortable with it.
- Scopes can be nested
- You can access outer scope but not inner scope.
- You can have multiple inner scopes
- This does indeed look like a tree of scopes when you look from outer to inner (top down)
- When you look the other way, inner to outer, you get a chain (bottom up) not a tree
2 Scope chains
- If you look for a value, JS walks up the scope chain; if nothing has that value you end up in the global scope.
- Closures occur when an inner scope references a variable in outer scope.
- This closes over the referenced variable.
4 Garbage Collection
- GC kicks in when all the code that might need a value has been executed
- This one is a good concept but a lot of people don’t understand it too well
- When a value is defined more than once in a scope chain, JS reaches the first one and stops; the top-most scope is not closed over.
- You can avoid a lot of problems here by emulating hoisting and putting all your vars at the top of scope. Use a linter to enforce this!
If you are still not sure:
npm install -g scope-chains-closures (self paced workshop)