Garbage Collection
AdvancedHow JavaScript decides which objects to free, and how a forgotten closure or event listener keeps memory alive.Builds on Primitive vs Reference Types, Closures, Higher-Order Functions
Empty
Empty
Empty
Empty
Spaceplay or pause←→previous or next stepRback to the start
Explanation
2 min read
On this page
What is garbage collection in JavaScript?
JavaScript manages memory for you. When you create an object, the engine allocates memory for it;
when the object can no longer be reached, the garbage collector frees that memory. There is no
delete/free for objects: you release memory by dropping the references to it.
How does the garbage collector decide what to free?
Modern engines use , based on reachability:
- Start from the roots: global variables, the variables of every function on the call stack,
and what the browser holds on to (
window, the DOM, event listeners, active timers). - Mark everything those roots reference, then everything those objects reference, and so on.
- Sweep: free every object that was not marked.
Two consequences come up in interviews:
- A closure is reachable through the function that holds it. While the function is reachable, every variable it uses stays in memory too.
- Collection happens when the engine decides, not when a reference is dropped. Engines also split the heap into generations and check young objects more often, since most objects die young.
What mistakes do people make with memory?
Mini example
function watchResize(onResize) { const controller = new AbortController(); window.addEventListener('resize', onResize, { signal: controller.signal }); return () => controller.abort(); // removes the listener} const stop = watchResize(() => console.log(window.innerWidth));// Later, when the component goes away:stop(); // the listener and everything it closes over can now be freedQuick check
After let user = { name: "Ali" }; const admin = user; user = null;, can the object be collected?
Further reading
All steps as text
- Step 1:
The garbage collector starts from roots: the global scope, the call stack, and browser objects like
window. Anything it can reach from them stays. - Step 2:
Creation phase:
user,adminandreportare reserved, andmakeReportis stored as a function.Lines 1–12
- Step 3:
An object is created in the heap. It is reachable, because the global variable
userpoints to it.Line 1
- Step 4:
A second object is created, and its
bossproperty holds a reference to the first one.Line 2
- Step 5:
user.team = adminpoints the first object back at the second. The two objects now form a cycle.Line 3
- Step 6:
user = nulldrops one reference, but Object @1 is still reachable: global →admin→boss. So it stays.Line 4
- Step 7:
Now no root leads to either object. They still point at each other, but the collector starts from the roots, so it frees both: cycles do not leak.
Line 5
- Step 8:
makeReport()is called, androwsis reserved in its scope.Line 12
- Step 9:
A big array of 100,000 items is created in the heap.
Line 8
- Step 10:
makeReport returns the arrow function into
report. Its scope stays alive because the closure usesrows, and so does the array.Lines 9–12
- Step 11:
report()runs and reachesrowsthrough its closure.Line 13
- Step 12:
It returns the length, and 100000 is printed.
Line 13
- Step 13:
report = nulldrops the only reference to the closure. The function, then its scope, then the array become unreachable and are freed.Line 14
- Step 14:
makeReport()runs again: a new scope, and a new big array.Line 16
- Step 15:
The returned function goes straight to
addEventListener, which stores it onwindow. Your code keeps no reference to it.Line 16
- Step 16:
The array is still reachable:
window→ listener → its scope →rows.windowlives as long as the page, so this memory is never freed.Line 16
- Step 17:
That is a memory leak: memory you no longer need, still reachable from a root. Keep a reference and call removeEventListener, or pass a
signaland abort it.