Skip to the workspace
Pebellslearn by building
Memory Management  ›  Lesson

Garbage Collection

Garbage Collection 12 min

javascript / Garbage Collection

Explore each scene at your own pace.

01 · Garbage Collection

Garbage Collection

Garbage Collection

Garbage collection reclaims memory associated with values that are no longer needed according to the runtime’s reachability rules. Collection timing is not a program-level guarantee.

Ask what still holds the object, rather than assuming that assigning null immediately frees it.

See the mechanism

Walk through the modelGarbage CollectionAuthored snapshots of the example; use Run below to test the code.
cachearticle object
local articlesame object
A reachable container can retain its values.
1 of 3

Follow one example

javascript

The Map holds a strong reference to the article value even after the local binding is cleared. Deleting the entry removes that path. Cycles alone do not necessarily leak: a modern tracing collector can reclaim an unreachable cycle. No line here proves when physical memory is reclaimed, and finalizers or weak references should not be used for required timely cleanup.

Predict, change and check

Predict: If two unreachable objects refer only to each other, does that cycle by itself guarantee a leak?

Test your explanation: Draw the cycle first with, then without, a root reference. For files, timers and listeners, perform explicit resource cleanup rather than waiting for garbage collection.

The tasks below ask you to explain that result and apply the idea to different inputs.

Apply and distinguish

Collection timing is not an application clock

A garbage collector reclaims eligible unreachable memory according to implementation strategies and runtime conditions. It does not give ordinary application code a promise that a particular value is collected immediately after one variable becomes null.

A test should check that a listener, timer, cache or closure no longer owns the resource under the application's policy. It should not require a finalizer to run by an exact timeout. Weak references and finalization facilities, where available, have constraints that make them unsuitable as the only mechanism for essential cleanup.

Check your understanding: State the input contract, identify the operation that changes the result, and give one boundary input that would distinguish the correct rule from the mistake described above.

Scene 1 of 2
Project context and further resources
Additional resources
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.