Blog/NotesConcept

Memory Leak in JavaScript: 4 Most Common Reasons

A quick guide to understanding the most common reasons and how to avoid Memory Leak in JavaScript with examples to build more robust web applications.

Expert

Anuj Sharma

Last Updated Jan 9, 2025


Memory Leak in JavaScript

Memory leaks in javascript are not very trivial to identify, since there are no significant explicit symptoms shown as part of the javascript because of this reason it's important to know the reasons for memory leaks in javascript. This helps to avoid such scenarios which can cause a memory leak in the first place.

Even though the javascript garbage collector, collects the garbage references at regular intervals, avoiding memory leak situations makes the web application lightweight. Let's check it out 

Memory Leak in JavaScript: 4 Most Common Reasons

Below are the common reasons and ways to avoid memory leak in javascript,

1. Global Variables without Identifiers (let, const or var)

Variables without let, const or var identifiers will automatically be part of a global scope and explicitly attached to the global scope. In such case, if they hold any reference of the scoped object then because of the global scope it won't allow the garbage collector to clean that variable even after the scope is completed. In such ways, it can also corrupt the global scope because of this explicit attachment to the global scope

Memory leak example

In this example, scoped variable is explicitly defined as global even after being declared inside the function. After the function finished execution, the inner scoped variable was collected by the garbage collector but scoped still there with global scope. 

var global = "I am global";

function scopedFunction() {
    // Global scoped explicitly, without identifier
    scoped = "I am scoped" 
    let inner = "inner";
    console.log("variables - ", scoped, inner);
}

scopedFunction();

Memory Leak in JavaScript

Here, variable name ascoped = "I am global variable" defined as part of the function without identifier, and it scoped to the global scope (window in browser), later the variable name changed to A_scoped = "I am global variable" Even after refresh the older variable was part of the global scope and that is why even after A_scoped in the code but ascoped was also available as part of the global scope. This way variables without identifiers can corrupt the global scope and cause memory leak.

How to avoid

Avoid creating variables without identifiers (let, const, var) and It's essential to have plugins or linters (like ESLint) as part of the project setup to catch this type of memory leak issue.

2. Not removing Event Listeners

It's important to remove event listeners once the DOM element is no longer part of the DOM means removed from the DOM otherwise they will listen for an infinite time until web pages are available. When the number of event listeners got increased they started draining the memory of the web browser to keep track of all the listeners which can hamper the performance of the web page as well.

Memory leak example

In this example, a click event listener is associated with the button. This event listener exists till the life cycle of the webpage even though the user goes into another part of the application.

const btn = document.getElementById("btn");

btn.addEventListener('click', () => {
    console.log('clicked');
});

//If the button is removed from the DOM, this event listener can cause a memory leak.

How to avoid

Always remove event listeners when an event is no longer required or when the DOM element is no longer part of the DOM for example Removing the DOM element, navigating to another page, logout or any error scenario.

const btn = document.getElementById("btn");

function printLog(){
    console.log('clicked');
}

btn.addEventListener('click', printLog);

// Remove event listener when event no longer required.
btn.removeEventListener("click", printLog);

3. Mindfully use the Closures

Closures can retain the references of objects which are part of its lexical scope for a longer duration and can cause memory leaks.

Memory leak in javascript

Memory leak example

function closuresExample() {
    const bigArr = new Array(1000).fill(5);

    return () => {
        console.log(bigArr);
    }
}

// printBigArr carry bigArr reference as part of the closure
// This closure reference won't allow the garbage collector to remove the reference of closureExample 

const printBigArr = closuresExample();
printBigArr();

How to avoid

It is important to mindfully use the closures, and make sure not to use any big memory-consuming object as part of the closures. It's better to create an object as part of the returned function itself so that the functions can be collected by the garbage collector if required since no linking is left.

4. Not cleared Timers & Intervals

Uncleared setInterval() keeps the associated object in memory and won't allow the garbage collector to collect the linked object. This may cause a memory leak, and it's important to clear the intervals to release the associated object.

Memory leak example

function printTimes(time) {
    console.log('Running - ', time);
}

const timer = setInterval(printTimes, 1000);
// If this interval call not cleared using clearInterval(timer)
// then it may cause memory leak

How to avoid

It's important to clear the associated intervals when it is no longer needed or in case of exception so that the garbage collector can collect the referenced object. This will prevent the chances of memory leaks.

function printTimes(time) {
    console.log('Running - ', time);
}

const timer = setInterval(printTimes, 1000);

// Clear the interval which stops the call and remove the reference.
clearInterval(timer);

 


Share this post now:

Flaunt You Expertise/Knowledge & Help your Peers

Sharing your knowledge will strengthen your expertise on topic. Consider writing a quick Blog/Notes to help frontend folks to ace Frontend Interviews.

Other Related Blogs

4 Ways to Reverse a String in JavaScript (JavaScript Interview)

Anuj Sharma

Last Updated Jan 4, 2025

Explore the most common ways to reverse a string in javascript including the most optimal way for frontend interviews with O(1) time complexity.

What is javascript:void(0) and How it Works?

Anuj Sharma

Last Updated Jan 5, 2025

A comprehensive explanation about using javascript:void(0) in javascript. When to use javascript:void(0) and how it works with examples of using it with anchor tag.

Explained Web Authorization Techniques - Session & JWT

Anuj Sharma

Last Updated Jan 2, 2025

Understand important web authorization techniques to enhance role-based authentication for any web application with popular techniques like Session & JSON Web Token (JWT)

Ultimate guide to REST API calls using Fetch: Machine Coding Essential

Vivek Chavan

Last Updated Dec 23, 2024

You will get a clear understanding about working with any rest api and common concepts asked during interviews

Understand JavaScript Date Object with Examples (for JavaScript Interviews)

Anuj Sharma

Last Updated Jan 9, 2025

Go through different ways to display dates using javascript date object. It covers examples of date object usage to understand the main concepts of javascript date object.

Promise Polyfill in JavaScript - Step by Step Explanation

Anuj Sharma

Last Updated Dec 27, 2024

An Interview-focused explanation of Promise Polyfill in JavaScript which helps to understand both Functional and ES6 custom promise implementation.

FrontendGeek
FrontendGeek

© 2024 FrontendGeek. All rights reserved