Closure
ELI5 — The Vibe Check
A closure is when a function remembers the variables from the scope it was created in, even after that scope is gone. It's like a function that carries a little backpack of variables with it wherever it goes. This is how React's useState hook works under the hood — the component function 'closes over' the state variable.
Real Talk
A closure is a function bundled together with its lexical environment — the variables that were in scope when the function was defined. Even when the outer function has finished executing, the inner function retains access to those variables. Closures enable data encapsulation, factory functions, and stateful callbacks.
Show Me The Code
function makeCounter() {
let count = 0 // count is enclosed
return {
increment: () => ++count,
decrement: () => --count,
value: () => count
}
}
const counter = makeCounter()
counter.increment() // 1
counter.increment() // 2
counter.value() // 2
// 'count' is inaccessible from outside
When You'll Hear This
React hooks rely on closures to capture state values.,Be careful with closures in loops — they capture by reference, not value.,Module patterns use closures to create private state.
Related Terms
Arrow Function
Arrow functions are a shorter way to write functions in JavaScript. Instead of writing 'function(x) { return x * 2 }' you write '(x) => x * 2'.
Callback
A callback is just a function you pass to another function, saying 'when you're done, call this.
Hoisting
Hoisting is JavaScript's weird quirk where variable and function declarations are mentally 'moved' to the top of their scope before code runs.
Scope
Scope is about where your variables are visible. Variables defined inside a function can't be seen outside it (that's function scope).