Closures Deep Dive
Definition
A closure is the combination of a function bundled together (enclosed) with references to its surrounding state (the lexical environment). A closure gives you access to an outer function's scope from an inner function, even after the outer function has finished executing.
Explain Like I'm New
Imagine a function is a tourist taking a photo. When the tourist (inner function) takes the photo (gets created), they capture the scenery around them (outer variables) in the picture. Years later, even if the tourist leaves the country (the outer function finishes and is removed from the Call Stack), they can still look at the photo and see the scenery EXACTLY as it was.
Real World Example
Creating private variables in factory functions, memoization, and React Hooks. `useState` relies heavily on closures to remember state between renders.
Common Use Cases
- •Currying
- •Memoization
- •Private variables
- •Event handlers in loops
Interactive Example
Interview Questions
basic
- Can you write a basic example of a closure?
intermediate
- Why did using `var` inside a `for` loop with a `setTimeout` cause bugs in older JavaScript?
advanced
- What is a 'Stale Closure' in the context of React Hooks?