Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 14.8 — Memory and Garbage Collection
JavaScript · Example 1 of 4

Mark-and-sweep on a toy heap

D and E point at each other, yet they're garbage: nothing reachable points to them. Reference counting would have kept them forever.

JavaScript frees memory automatically: the garbage collector keeps every object that can be reached from the roots (globals, the running functions, live closures and the DOM) and reclaims the rest. A memory leak is an object you no longer need that is still reachable, most often through a forgotten listener, timer, closure, cache or detached DOM node.

Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.

Ready for more? This phase has 5 hands-on exercises with automatic checks.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Rewrite function track() { setInterval(() => console.log("tick"), 1000); } so the caller can stop it, and show the stop call.

02

This code keeps every removed card in memory: const cards = []; function add() { const c = document.createElement("div"); cards.push(c); document.body.append(c); } function removeAll() { cards.forEach((c) => c.remove()); }. Fix removeAll so the cards can be collected.

Explain it without notes

01

How does the JavaScript garbage collector decide what to free?

02

Why does mark-and-sweep handle circular references when reference counting doesn't?

03

Name four common sources of memory leaks in browser code and how to fix each.

04

How would you find a memory leak in a web app?

Mark-and-sweep on a toy heap

Preview

Press Run to see the page.

Console

Nothing logged yet.

Expected console output

reachable: [ 'A', 'B', 'C' ]
garbage: [ 'D', 'E', 'F' ]
after A drops B: [ 'A' ] garbage: [ 'B', 'C', 'D', 'E', 'F' ]