Memory Management in JavaScript – Avoid 4 Common Memory Leaks?

JavaScript is a great language. From web to mobile apps, it’s been used for everything from games to system automation. However, as with any programming language, some parts tend to come with their own set of issues.

3 mins read
December 3, 2021

In the world of web development, the problem of memory leaks is very common. It doesn’t matter if the language you are using is very well memory-managed, there can still be some memory leaks. All over the world, software, websites, and apps suffer from common problems such as crashes, slowdowns, and high latency that are usually caused by leaks.

When an application is running, there may be some certain kind of memory that the operating system may reject due to its unusability. A memory leak occurs when a no longer needed memory is still not released from the system and reserving the system space for no reason.

There are different reasons for memory leaks in different programming languages. Here, we will focus on JavaScript and explore the four common memory leaks in JavaScript.

The Four Types of Common Memory Leaks:

Global Variables

JavaScript is very good at handling undeclared variables. If the JavaScript sees an undeclared variable, it creates a new variable inside the Global Object. A global object is a primary environment where the application with the undeclared variable is running. If the application is a Browser, then the global object can be considered as a Window. Such a variable doesn’t get collected by the Garbage and is considered a memory leak.

How can we prevent the case of a global variable?: The developers can use the “Strict Mode” to stop all the accidental leaks that could happen.

Forgotten Timers or Callbacks

In JavaScript, developers mostly use the setInterval feature. It helps the application to take a callback. If an instance of a callback is unreachable then the library will make the callback itself unreachable as well. But still, certain functions in the code such as ‘timers’ reference to nodes or data that are no longer required. If an object in such a code is removed in the future, the block that’s present in the object becomes unnecessary. But if the block (handler) in that object is still active, then the garbage collector won’t connect it. As a result, it creates a memory leak.

How to prevent that:

The developer who’s using the observer function needs to understand that the handlers in an object will need an explicit call to remove them once their work is done.

Even though today’s browsers are very advanced in getting rid of handlers automatically for you, it is still the preferred practice to eradicate observers when there is no use for the object.

You can also make use of the jQuery APIs which will help you remove the listeners before a node is becoming obsolete.

Below is the Snippet for Example

// Bad Practices

var counter = 0;
function setCallback() {
    console.log(++counter)
}

setInterval(setCallback, 1000);

// Good Practices

var counter = 0;
function setCallback() {
    console.log(++counter)
}

var interval = setInterval(setCallback, 1000);

clearInterval(interval); // Call predefined clearInterval method to clear the interval once task has been done

Closures

Closures are a very used and important function in JavaScript. It picks the variables from its parent function. In a recent study,  it was found that a memory leak can occur in an enclosure depending on how the program is written.

How can We Prevent it?

For a developer using the Closure, the function is so common that it can’t be avoided. Hence, he/she needs to remember the creation time of the closure function as well as which object it retains. Secondly, he also needs to make a check on the total lifespan of the closure and what were its uses.

Below is the Snippet for Example

// Bad Practices

function outer() {

    console.log(‘Outer’)

    function inner() {
        console.log(‘Inner’)
    }

    inner();
}

// Good Practices

function outer() {

    console.log(‘Outer’)

    function inner() {
        console.log(‘Inner’)
    }

    // inner(); Avoid this auto calling itself when calling a function
}

Out of DOM References

JavaScript has its reference and a DOM node can share the same reference with it. The Document Object Model (DOM) refers to a programming interface that defines an accurate and actual structure of HTML and XML documents like how documents are accessed and manipulated.

It represents a document as a tree of nodes and enables you to effectively edit, remove or update any part of the document. If that’s the case then the node won’t be collected by Garbage regardless of whether it was removed from the DOM tree or not.

How can We Prevent it?

The easy way to do this is to move the DOM reference to the local scope. That way, it won’t be sharing its reference with the JavaScript itself. Therefore, the DOM will be removed from the memory when the function is removed.

Conclusion

If your app is a non-trivial one, it might seem pretty hard to manage memory leak issues in JavaScript. That’s why the developer needs to analyze the written code closely and tweak it, so the instances of memory leaks can be prevented from happening in the first place. The more instances of memory leaks, the worse user experience your end-users will receive. Therefore, the significance of handling such issues is very high.

Web Development

Rajan Kumar

Team Leader (Front-End)

Working in the software industry for a decade, Rajan has led various large and complex projects wisely. Currently, he is leading a front-end development team at Logiciel. His expertise lies in engineering scalable and real-time apps with advanced technologies like JavaScript, Angular, AngularJS & React. He holds a master’s degree in Computer Application and this helps him thrive in fast-paced development environments easily. He has a commendable influencing potential that boosts up the positive approach among his teammates. His determination towards his work and organization makes him one of the best employees of our company.

    Related Articles