Functions and closures
How functions remember the scope they were created in, and how to use that for private state and memoization.
Updated
A closure is a function together with the variables it could see where it was created. Closures power private state, factories, memoization, event handlers and most of the patterns modern frameworks are built on. Once you can see them, a lot of JavaScript stops feeling like magic.
Functions are values
Functions can be stored in variables, passed to other functions and returned from them. There are three common ways to write one. Declarations are hoisted, so you can call them before the line where they appear. Arrow functions are not hoisted and do not have their own this.
function add(a, b) {
return a + b
}Lexical scope
JavaScript resolves a variable name by looking at where the code is written, not where it is called from. An inner function can read the variables of every function that surrounds it, all the way out to the module.
const greeting = 'Hello'
function outer() {
const name = 'Ada'
function inner() {
return `${greeting}, ${name}`
}
return inner()
}
outer() // 'Hello, Ada'Closures keep variables alive
When a function is returned, it keeps access to the variables of the scope it came from, even after that scope has finished running. Every call creates a fresh scope, so every returned function gets its own private set of variables.
count lives in the closure. Nothing outside createCounter can read or change it directly.Practical pattern: memoization
A closure can hold a cache. A memoized function remembers previous results and skips the work when it sees the same input again, which pays off for expensive calculations that are called repeatedly with the same arguments.
export function memoize(fn) {
const cache = new Map()
return (arg) => {
if (cache.has(arg)) return cache.get(arg)
const result = fn(arg)
cache.set(arg, result)
return result
}
}The classic loop trap
Before let existed, every iteration of a loop shared a single var variable. Callbacks created inside the loop all closed over that one variable and saw its final value when they eventually ran.
let creates a new binding for every iteration, so each callback keeps its own value.Closures in React
Every render of a React component creates new functions that close over that render's props and state. A timer or effect created during an earlier render therefore sees stale values. Updater functions sidestep the problem because React passes in the latest state.
function Timer() {
const [seconds, setSeconds] = useState(0)
useEffect(() => {
const id = setInterval(() => {
setSeconds((current) => current + 1)
}, 1000)
return () => clearInterval(id)
}, [])
return <p>{seconds} seconds</p>
}Summary
- Scope is lexical: what a function can see depends on where it is written.
- Returned functions keep their surrounding variables alive.
- Closures give you private state without classes.
- In React, prefer updater functions when a callback outlives a render.
Finished this lesson?
Mark it complete to track your progress across every track in the curriculum.