Memory leaks
Learn common memory-leak causes and how to prevent them.
Memory leak
A memory leak happens when a program cannot return unused memory to the garbage collector. In JavaScript the garbage collector reclaims data that is no longer reachable.
But if a reference is kept alive by mistake, that data is never freed. Over time the accumulated data slows the page and may crash it. Cleaning up timers and listeners matters.
Preventing leaks
To prevent leaks, break unnecessary references. Stop timers with clearInterval and remove listeners with removeEventListener.
When holding large objects, WeakMap or WeakSet let the value be collected automatically once the key is gone. This is useful for caches and similar structures, and it lowers the risk of leaks.
Exercise Listener and cleanup
Write a function named setupLogger. It takes element, adds a click listener, and returns a cleanup function named cleanup. The cleanup removes the listener with removeEventListener.
Show example solution
Keep the log function; add with addEventListener, return function cleanup() that calls removeEventListener.
Example solution:
function setupLogger(element) {
const log = () => console.log("active", element.id);
element.addEventListener("click", log);
return function cleanup() {
element.removeEventListener("click", log);
};
}
Test yourself
-
Which of the following causes a memory leak?
- Using local variables
- Not clearing an unused timer
- Declaring variables with const
- Using arrow functions
Show answer
Not clearing an unused timer — Correct! An uncleared timer keeps its references and the memory alive.
-
Clear the timer
function stop() { ____; timer = null; }Show answer
function stop() { clearInterval(timer); timer = null; } -
Match the memory terms
- garbage collection
- frees unused memory
- closure
- keeps scope alive
- WeakMap
- weak reference
- retained reference
- held reference