Skip to content

Closure

Spicy — senior dev territoryFrontend

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.

Made with passive-aggressive love by manoga.digital. Powered by Claude.