Building Your Learning Module...
Getting things ready for you!
Find videos you like?
Save to resource drawer for future reference!
Garbage collection (GC) is JavaScript's automatic memory management system. Unlike languages like C where you manually allocate and free memory, JavaScript automatically finds and removes objects that are no longer being used. This happens behind the scenes without you having to do anything - but understanding how it works helps you write more efficient code!
Most JavaScript engines (like V8 in Chrome) use a mark-and-sweep algorithm. Here's how it works:
The garbage collector starts from roots (global objects, currently executing functions) and "marks" all objects it can reach by following references.
What are roots?
After marking, the garbage collector "sweeps" through memory and removes all objects that were NOT marked. These unmarked objects are unreachable and can be safely deleted.
Result:
Some engines also compact memory by moving live objects together, eliminating gaps left by deleted objects. This prevents memory fragmentation.
The key concept in garbage collection is reachability. An object is "reachable" if you can access it from a root by following references. Reachable objects are kept, unreachable objects are deleted.
Global Variables
let user = { name: 'Alice' };
// Reachable via 'user' variableReferenced Objects
let a = { value: 1 };
let b = { ref: a }; // a is reachable via bActive Functions
function process() {
let data = [1, 2, 3];
// 'data' is reachable while function runs
}Nulled References
let user = { name: 'Alice' };
user = null; // Object becomes unreachableLocal Variables After Function Ends
function create() {
let temp = { data: 'big' };
return null;
}
create(); // 'temp' becomes unreachableCircular References (No External Refs)
let a = {};
let b = {};
a.ref = b;
b.ref = a;
a = null; b = null; // Both unreachableModern engines like V8 use generational garbage collection. The idea: most objects die young. By separating objects by age, we can collect frequently for young objects and rarely for old ones.
Newly created objects start here. This space is small and collected frequently (minor GC).
Long-lived objects that survived multiple minor GCs. This space is larger and collected infrequently (major GC).
Garbage collection pauses your JavaScript execution while it runs. These pauses are usually very short (milliseconds), but can cause performance issues if:
Cause: Creating many short-lived objects rapidly
Impact: Constant minor GC pauses add up
Solution: Reduce object allocations, reuse objects (object pooling)
Cause: Very large heap or old generation full of objects
Impact: Major GC pauses can freeze UI for noticeable time
Solution: Reduce total memory usage, break up large data structures
Cause: Objects never become unreachable (forgotten references)
Impact: Heap grows, GC works harder, pauses get longer
Solution: Fix memory leaks (see Memory Leaks topic)
Create fewer objects, especially in hot paths (loops, frequently called functions). Reuse objects when possible instead of creating new ones.
Use local variables in functions instead of global variables. Local variables become unreachable quickly after the function returns.
When done with large objects, set references to null to help GC identify them as unreachable sooner. Especially useful for global variables or long-lived objects.
For frequently created/destroyed objects (e.g., game entities, particles), maintain a pool of reusable objects instead of constantly creating new ones.
There's no reliable way to force garbage collection in JavaScript. The engine decides when to run GC based on heuristics. Trust the GC to do its job!
GC removes unreachable objects
Happens automatically, periodically
Uses mark-and-sweep algorithm
Keep: Objects reachable from roots
Delete: Unreachable objects
Circular refs are handled
Young generation: frequent, fast
Old generation: rare, slower
Most objects die young
Minimize object creation
Use local variables
Null out large objects when done