We are thrilled to inform you that Lancecourse is NOW INIT Academy — this aligns our name with our next goals — Read more.

It seems like you are using an ad blocker. To enhance your experience and support our website, please consider:

  1. Signing in to disable ads on our site.
  2. Sign up if you don't have an account yet.
  3. Or, disable your ad blocker by doing this:
    • Click on the ad blocker icon in your browser's toolbar.
    • Select "Pause on this site" or a similar option for INITAcademy.org.

Javascript in 100 bits

Course by zooboole,

Last Updated on 2025-01-28 08:04:00

Lesson 98 – JavaScript Memory Management & Garbage Collection

Memory management is a crucial aspect of software development. In JavaScript, memory allocation and deallocation are handled automatically through a process called garbage collection. However, understanding how memory works under the hood can help you write more efficient and memory-safe applications.


What Is Memory Management?

Memory management is the process of allocating, using, and releasing memory in your program.

In JavaScript, this typically involves two major phases:

  1. Allocation – Reserving memory for variables, objects, and functions.
  2. Deallocation (Garbage Collection) – Releasing memory that is no longer in use.

Memory Life Cycle

Every time you create a variable or object, memory is allocated to store it. That memory is kept until it is no longer referenced or needed.

Phases:

  1. Allocate memory when declaring variables.
  2. Use the memory by performing operations.
  3. Free the memory when it's no longer needed.

Garbage Collection in JavaScript

Garbage collection (GC) is the process of automatically identifying and reclaiming memory that is no longer in use.

Key GC Concept: Reachability

The JavaScript engine determines which objects are “reachable” and keeps them in memory. If an object is no longer reachable, it is eligible for garbage collection.

let user = {
  name: "Alice"
};

user = null; // The object is now unreachable and can be collected

Garbage Collection Algorithms

Most modern JavaScript engines use these two algorithms:

  • Mark-and-Sweep: Marks reachable objects and sweeps (clears) the unreachable ones.
  • Reference Counting: Counts the number of references to each object and collects the ones with zero references (less common due to circular reference issues).

Common Memory Leaks in JavaScript

  1. Global Variables – Accidentally creating globals keeps them in memory.
  2. Closures – Unused closures can retain memory unnecessarily.
  3. Detached DOM Elements – If references to removed DOM nodes persist, memory leaks can occur.
  4. Timers and Callbacks – setInterval or setTimeout not cleared properly.

Example Memory Leak with setInterval

function startLeaking() {
  setInterval(() => {
    console.log("Still here!");
  }, 1000);
}

If setInterval is not cleared with clearInterval, the memory used by the callback function will never be freed.


Best Practices to Avoid Memory Leaks

  • Avoid unnecessary global variables.
  • Remove event listeners when not needed.
  • Nullify references to unused objects.
  • Clear intervals and timeouts when not needed.
  • Be cautious with closures that retain large objects.

Summary

  • JavaScript handles memory automatically, but poor code practices can lead to memory leaks.
  • Understanding how garbage collection works (especially reachability) helps prevent issues.
  • Keep your code clean, manage references wisely, and always release resources.

Try Your Hand

Task: Create a timer that logs a message every second and then stops after 5 seconds using setInterval and clearInterval.

let count = 0;
const intervalId = setInterval(() => {
  console.log("Counting:", count);
  count++;
  if (count >= 5) {
    clearInterval(intervalId);
  }
}, 1000);

In This Lesson, You Learned:

  • What memory management is in JavaScript.
  • How the garbage collector works (mark-and-sweep, reference counting).
  • Common causes of memory leaks.
  • Best practices to write memory-efficient JavaScript.