Scope types
| Type | Created by | Notes |
|---|---|---|
| Global | Top-level code | Accessible everywhere |
| Function | function keyword | Each call gets its own scope |
| Block | {}, if, for | Only let/const are block-scoped |
| Module | ES module file | Private by default |
Closures
Common use cases
- Data encapsulation — private variables
- Factory functions — create customized functions
- Memoization — cache previous results
- Partial application / currying
Classic closure gotcha
Scope chain
When a variable is accessed, JS looks up the scope chain from innermost to outermost until it finds the variable or reaches the global scope.Common interview questions
What is a closure?
What is a closure?
A closure is a function bundled together with references to its surrounding lexical environment. It allows a function to access variables from its outer scope even after the outer function has finished executing.
How do closures relate to memory leaks?
How do closures relate to memory leaks?
Closures can cause memory leaks if a closure holds a reference to a large object that is no longer needed. The garbage collector cannot reclaim the object because the closure still references it. The fix is to set the reference to
null when it’s no longer needed.What is the difference between lexical scope and dynamic scope?
What is the difference between lexical scope and dynamic scope?
JavaScript uses lexical (static) scope — the scope of a variable is determined at write time by where the variable is declared in the source code. Dynamic scope (not used in JS) would determine scope at runtime based on the call stack. The
this keyword behaves somewhat like dynamic scope, which is why arrow functions capture this lexically instead.