Sobes.tech
Senior

What is a memory leak and how does the garbage collector work in JavaScript?

sobes.tech AI

Answer from AI

A memory leak in JavaScript is a situation where memory that is no longer needed by the program is not released, leading to a gradual increase in memory consumption and potentially causing the application to slow down or crash.

The Garbage Collector (GC) in JavaScript automatically frees memory occupied by objects that are no longer reachable from root references (such as global variables, call stack).

The main algorithm is reachability counting:

  • GC starts from root objects and marks all objects that can be reached via references.
  • All unmarked objects are considered unreachable, and their memory is freed.

Example of a memory leak:

function createClosure() {
  let largeArray = new Array(1000000).fill('*');
  return function() {
    console.log(largeArray.length);
  };
}

const closure = createClosure();
// largeArray will not be freed as long as closure exists

Here, largeArray remains in memory because the closure holds a reference to it.

To avoid leaks, you should:

  • Remove unnecessary references (e.g., nullify variables).
  • Avoid global variables.
  • Be cautious with closures and event handlers.

The Garbage Collector works automatically, but understanding its principles helps in writing efficient and safe code.

What is a memory leak and how does the garbage… - sobes.tech