Node.jsInterview preparation
Intermediate·Concept·2 min read

How do garbage collection and memory leaks work?

Practice this question

Definition:

Garbage collection automatically reclaims memory that can no longer be reached by running code. A memory leak happens when the program keeps a reference to data it no longer needs, so the collector must treat that data as still usable. Increasing the heap limit may delay failure but does not remove the unwanted references.

Key points:

  • Garbage collection frees objects that are no longer reachable.

  • A cache, listener or timer can keep unused data reachable.

  • Remove unused listeners, clear timers and put size limits on caches.

  • Circular references alone are not a leak when the entire cycle becomes unreachable.

  • Look at trends after garbage collection, not just temporary memory growth during a busy request.

Interview point:

  • Explain who still owns the leaked reference; “JavaScript has GC” is not a guarantee against leaks.
Adapted from 01_JAVASCRIPT_TYPESCRIPT.md · “How do garbage collection and memory leaks work?”. Code examples are study fragments. Difficulty and core labels are editorial estimates; version-specific behavior should be checked against your project.