Global variables. Hopefully, no one uses var in 2024, but also it's important to be mindful the situation in the example.
function leak() {
leakyVar = 'I am a global now'
} Uncleared timers, setInterval and setTimeout should always be paired with the cleanup functions clearInterval and clearTimeout.
const intervalId = setInterval(() => {
// Some operation
}, 1000)
// Potential leak without the following line
clearInterval(intervalId) Detached DOM elements. If a DOM element is removed from the page but is still referenced in JavaScript, it remains in memory. This applies to frameworks or any library that uses references to DOM elements.
let button = document.getElementById('button')
document.body.removeChild(button)
// Potential leak without the following line
button = null Unremoved event listeners.
const handler = () => {
console.log('Clicked')
}
button.addEventListener('click', handler)
// Potential leak without the following line
button.removeEventListener('click', handler) Closures retaining scope. Closures can accidentally keep large objects in memory.
function outer() {
const largeData = new Array(1000000)
return function inner() {
return largeData[0]
}
}
const leak = outer() // largeData is retained in memory