Stop caches growing forever: a small LRU
A Map keeps insertion order (Topic 14.3), so its first key is always the least recently used. b was evicted when d arrived, and memory stays bounded.
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.
Rewrite function track() { setInterval(() => console.log("tick"), 1000); } so the caller can stop it, and show the stop call.
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
How does the JavaScript garbage collector decide what to free?
Why does mark-and-sweep handle circular references when reference counting doesn't?
Name four common sources of memory leaks in browser code and how to fix each.
How would you find a memory leak in a web app?
Preview
Console
Nothing logged yet.Expected console output
[ 'c', 'a', 'd' ]
undefined 3