What is a closure? Give a practical use.
30-second answer: A closure is a function that remembers the variables from where it was created, even after the outer function has finished. It gives you private state and function factories.
A closure is a function bundled with the variables of the scope where it was defined. The function keeps access to those variables even after the outer function has returned.
Typical uses: private state, function factories, memoization and callbacks that remember configuration.
function counter() {
let n = 0;
return () => ++n;
}
const next = counter();
next(); // 1
next(); // 2def counter():
n = 0
def inc():
nonlocal n
n += 1
return n
return inc
next_id = counter()
next_id() # 1
next_id() # 2function counter(): () => number {
let n = 0;
return () => ++n;
}
const next = counter();
next(); // 1Follow-up questions interviewers ask next
- What goes wrong with var in a loop and a closure?
- Can closures cause memory leaks?
- Where do closures bite in React hooks?