Skip to content
JavaScript·Advanced·Coding·1 min read

Can closures cause memory leaks?

Short interview answer

A reachable closure keeps its referenced environment reachable. That is intentional, but retaining a long-lived callback can also retain large objects unnecessarily. Remove obsolete listeners and timers, and avoid capturing more state than the callback needs.

Example

JavaScript
function attach(node) {  const big = new Array(1_000_000).fill('x'); // captured by `handler`  const handler = () => console.log(big.length);  node.addEventListener('click', handler);  return () => node.removeEventListener('click', handler); // call on teardown}

Key takeaway

Explain the underlying mental model clearly, then support it with a concrete example and its trade-offs.

← Back to Closures

Related questions