# Memory & Garbage Collection

> Understand how JavaScript automatically manages memory, references, and the Mark-and-Sweep garbage collection algorithm.

Subject: JavaScript | Lesson 52 of 63 | 6 min read
Interactive lesson: https://codewithanimation.in/javascript/memory-and-garbage-collection
Previous: [Error Handling: try/catch](https://codewithanimation.in/javascript/error-handling.md) | Next: [Regular Expressions](https://codewithanimation.in/javascript/regular-expressions.md)

## Automatic Memory Management

Low-level languages like C require you to manually allocate and free memory in RAM. If you forget to free it, your app leaks memory and eventually crashes.

JavaScript handles this automatically using a **Garbage Collector (GC)**. When you create an object, JS allocates memory for it. When the object is no longer needed, the GC automatically detects it and frees the memory.

## The Concept of Reachability

How does the GC know when an object is 'no longer needed'?

It uses the concept of **Reachability**. An object is reachable if you can trace a path to it starting from the 'roots' (like the global `window` object, or variables currently in scope).

If an object has zero references pointing to it from a root, it is unreachable. The GC considers it garbage.

## The Mark-and-Sweep Algorithm

Modern JavaScript engines use a 'Mark-and-Sweep' algorithm.

1. **Mark**: The GC starts at the roots and traverses every single reference, 'marking' every object it finds as reachable.

2. **Sweep**: It then scans the entire memory heap. Any object that is *not* marked is immediately deleted, freeing up RAM.

```javascript
let user = { name: 'Alex' };
// The object is reachable via the 'user' variable.

user = null;
// The reference is severed. The object is now unreachable and will be swept.
```

## Common mistake: Memory Leaks

Even with automatic GC, you can still cause memory leaks. A leak happens when you accidentally keep a reference to an object that you don't need anymore.

Common causes include forgetting to call `clearInterval()`, or failing to call `removeEventListener()` on DOM nodes that you've deleted from the page.

## Tip: WeakMap and WeakSet

If you want to attach data to an object without preventing it from being garbage collected, use a `WeakMap`. References inside a WeakMap are 'weak'-if there are no other references to the object, it will be garbage collected and automatically removed from the WeakMap!

## Try it: The Mark and Sweep

Study the architecture diagram below. It contrasts a healthy, reachable object graph with one that has had a reference severed, leaving a detached object stranded and targeted for deletion.

The animation is on the lesson page and is not part of this text version: https://codewithanimation.in/javascript/memory-and-garbage-collection

## Check yourself

### Question 1

What is the primary condition for an object to be Garbage Collected in JavaScript?

- A. It must become completely unreachable from any 'root'.
- B. It must be explicitly deleted using the `delete` keyword.
- C. It must be older than 5 minutes.

Correct answer: A

If the GC cannot find a path from the roots (global scope, current function scope) to an object, that object is considered unreachable garbage.

- Why not B: Incorrect. `delete` removes object properties, it doesn't free the object itself.
- Why not C: Incorrect. Age is irrelevant; only reachability matters.

### Question 2

What does the 'Mark' phase of the Mark-and-Sweep algorithm do?

- A. It traces all references starting from the roots and marks every object it can reach.
- B. It marks old memory blocks for deletion.
- C. It marks your variables as const or let.

Correct answer: A

The algorithm safely assumes everything is garbage, *unless* it can prove otherwise by walking the reference tree from the roots and marking what it touches.

- Why not B: Incorrect. The sweep phase handles deletion. Marking is for tracking what is *safe*.
- Why not C: Incorrect. That is syntax parsing, not memory management.

### Question 3

Which of the following is a classic cause of a JavaScript memory leak?

- A. Forgetting to remove an event listener on a DOM element before removing the element from the DOM.
- B. Setting a variable to null.
- C. Using too many nested functions.

Correct answer: A

If a global event listener (like on the `window` or `document`) still references a detached DOM element, the Garbage Collector cannot sweep the element because the event system still holds a 'root' reference to it.

- Why not B: Incorrect. Setting a variable to null helps *prevent* memory leaks by severing references.
- Why not C: Incorrect. Nesting functions does not cause memory leaks unless you form unresolved closures holding heavy data.

## Remember this

- JavaScript automatically handles memory allocation and freeing via a Garbage Collector.
- The primary metric for memory retention is **Reachability**.
- If an object cannot be reached by following references from a root, it is garbage collected.
- Modern engines use the **Mark-and-Sweep** algorithm to find and delete unreachable objects.
- Memory leaks happen when you unintentionally maintain a reference to an object you no longer need (e.g., uncleared intervals or event listeners).
