Member-only story

5 Common JavaScript Memory Mistakes

Jose Granja
Better Programming
Published in
6 min readMar 1, 2021
Computer chip
Photo by Possessed Photography on Unsplash.

JavaScript doesn’t provide any memory management primitives. Instead, memory is managed by the JavaScript VM through a memory reclaim process. That process is known as Garbage Collection.

Since we can’t force it to run, how do we know it will work properly? What do we know about it?

  • Script execution is paused during the process.
  • It frees memory for unreachable resources.
  • It is non-deterministic.
  • It will not inspect the whole memory in one go but will run in multiple cycles.
  • It is unpredictable. It will execute when necessary.

Does that mean we don’t have to worry about resources and memory allocation? Certainly not. If you aren’t careful, you might create some memory leaks.

What Is a Memory Leak?

A memory leak is an allocated piece of memory that the software is not able to reclaim.

That Javascript provides you with a garbage collection process doesn’t mean you are safe from memory leaks. In order to be eligible for garbage collection, the object must not be referenced elsewhere. If you hold references to unused resources, you will be preventing those resources from being unallocated. That is known as unintentional memory retention.

Leaking memory may result in more frequent garbage collector runs. As this process will prevent scripts from running it might slow down your web app. That will make it less snappy, which will be noticed by the user. It can even lead to your web app crashing.

How can we prevent our web app from leaking memory? We have to avoid the retention of unnecessary resources. Let’s look at the most common scenarios where this might happen.

1. Timer Listeners

Let’s look at the setInterval timer. It is a commonly used Web API feature.

“The setInterval() method, offered on the Window and Worker interfaces, repeatedly calls a function or executes a code snippet, with a fixed time delay between each call. It returns an interval ID which uniquely identifies the interval, so…

Create an account to read the full story.

The author made this story available to Medium members only.
If you’re new to Medium, create a new account to read this story on us.

Or, continue in mobile web

Already have an account? Sign in

Jose Granja
Jose Granja

Written by Jose Granja

Top Writer @Medium | 1M+ Views | Lead FE @Lingoda | I write weekly about web-development topics 📰 Support me at https://dioxmio.medium.com/membership 🙇

Responses (5)

Write a response