How do garbage collection and memory leaks work?
Try code in the playgroundUnderstand 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.
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.
Turn this concept into a clear answer.
- 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?”. Examples are study fragments; framework behavior can depend on your version.