What is a memory leak in JavaScript, given that it has automatic garbage collection?
Short answer
A memory leak happens when objects remain reachable (and therefore never collected) even though the program logically no longer needs them — typically because a lingering reference (a global variable, a forgotten event listener, or a closure) accidentally keeps them alive.
Advertisement
AModel answer
A memory leak happens when objects remain reachable (and therefore never collected) even though the program logically no longer needs them — typically because a lingering reference (a global variable, a forgotten event listener, or a closure) accidentally keeps them alive.
function setup() {
const bigData = new Array(1000000).fill('x');
window.leaked = bigData; // accidental global reference keeps it alive forever
}Real-world example
Diagnosing why a single-page app's memory usage keeps climbing the longer a user stays on the page.
Likely follow-ups
- What browser tool would you use to find the source of a memory leak?
Related topics