LESSON 22 / 22·2 min readIntermediate

How do garbage collection and memory leaks work?

Try code in the playground
01 Understand02 Recall03 Prepare

Understand the concept

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.

Important ideas

  • 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.

PAUSE & RECALL

Can you explain it without the notes?

How do garbage collection and memory leaks work?

Use your own words. Explain an example and one limitation before checking the explanation.

Check your explanation

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.

CONNECT IT TO YOUR INTERVIEW

Turn this concept into a clear answer.

  • Explain who still owns the leaked reference; “JavaScript has GC” is not a guarantee against leaks.
Practice this concept
YOUR NEXT STEP

You’ve reached the end of this guide.

Prepare for Node.js interviews

Adapted from 01_JAVASCRIPT_TYPESCRIPT.md · “How do garbage collection and memory leaks work?”. Examples are study fragments; framework behavior can depend on your version.