Functions, Scope & Object Model

Memory, References & Garbage Collection

JavaScript automatically frees values that are no longer reachable, but automatic garbage collection does not prevent leaks. A leak is unneeded data that remains reachable.
  • Reachability determines collection
  • References make mutation visible
  • Closures can keep data alive
  • Caches need eviction
  • Event listeners need cleanup
Reachability
The large object stays alive because a root can still reach it through the callback.
Unbounded cache smell
const cache = new Map()

function remember(key, value) {
  cache.set(key, value)
}

// Unless entries are removed, this grows for the lifetime of the process/page.
A cache without eviction is just a leak with better marketing.
Common leak sources
SourceWhy it leaksMitigation
Global Map cacheEntries never removedTTL/size limit/clear
Event listenerCallback retainedremove listener / abort signal
Timer/intervalCallback retainedclear timeout/interval
ClosureCaptures large objectCapture less / cleanup
Detached DOMJS still references nodeRelease references
Sources
  • MDN JavaScript Guide and ReferenceMemory management
  • The Modern JavaScript TutorialGarbage collection
  • Node.js Documentation and Learn Node.jsDiagnostics and memory