JavaScript Memory Management & Garbage Collection


What is Memory Management?

Memory management in JavaScript refers to the process of allocating and freeing memory during the execution of a program.

  • JavaScript automatically allocates memory when values are created.
  • JavaScript automatically frees memory (via garbage collection) when values are no longer needed.


1. Memory Allocation

JavaScript allocates memory when you:

// Primitive values
let a = 42;
let name = "Alice";
// Objects and arrays
let user = { name: "Bob" };
let arr = [1, 2, 3];

JavaScript handles the allocation behind the scenes.



2. Garbage Collection (GC)



What is Garbage Collection?

Garbage Collection is the process of automatically freeing up memory by removing objects that are no longer accessible.

JavaScript uses algorithms (like mark-and-sweep) to do this efficiently.



Mark-and-Sweep Algorithm

1. GC starts with global/root references.

2. It "marks" all values that are reachable (via variables, objects, closures).

3. Anything not marked (i.e., unreachable) gets "swept" and deleted.

let user = {
name: "Eve",
};
user = null; // Memory will be freed, as there's no reference to the
object

The object is unreachable, so it's eligible for garbage collection.



3. Common Memory Leaks

Even with automatic GC, memory leaks can still happen!



1. Forgotten timers or intervals

setInterval(() => {
console.log("Still running...");
}, 1000); //  Never cleared

Always use clearInterval() when done.



2. Detached DOM nodes

let element = document.getElementById("myDiv");
element.remove(); // Removed from DOM
// But still referenced in memory
console.log(element); //  Prevents GC

Set references to null if no longer needed.



3. Closures holding memory

function outer() {
let bigData = new Array(1000000).fill("*");
return function inner() {
console.log("Still using closure");
};
}
const hold = outer(); // bigData is not freed due to closure

Avoid keeping unused data in closures.



Best Practices for Efficient Memory Use

  • Dereference objects: obj = null;
  • Clear intervals and timeouts
  • Remove unused event listeners
  • Be cautious with global variables
  • Avoid memory-heavy closures


Tools to Track Memory

  • Chrome DevTools → Performance & Memory Tabs
  • Heap Snapshots → track retained memory
  • Lighthouse → performance and memory audits