Day 25: Memory
Tags: day25, javascript, 100daysofcode
Published: 2023-08-14 14:00:00

Memory 🧠 management is a critical aspect of any programming language, and JavaScript is no exception. Understanding how JavaScript handles memory is essential for building efficient and performant applications. 

## 📦 Memory Allocation 

In JavaScript, memory is allocated for variables and objects as needed. One of the key concepts in memory allocation is the difference between the stack and the heap.

### 🥞 The Stack 

The stack is a region of memory that is used for storing primitive data types and function call information. Variables with a known, fixed size, such as numbers and booleans, are stored on the stack. This memory is managed efficiently, as it follows a last-in, first-out (LIFO) approach.

```javascript
function calculateSum(a, b) {
  // `a` and `b` are stored on the stack
  return a + b;
}
```

### 🗄️ The Heap 

The heap is a region of memory used for storing objects and variables with dynamic sizes. Objects like arrays and objects created using the `new` keyword are stored on the heap. This memory requires more complex management, as it involves tracking references and ensuring proper cleanup.

```javascript
const largeArray = [1, 2, 3, 4, 5];
// `largeArray` is stored on the heap
```

## 🔄 Memory Life Cycle


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/sk756uikx7wyx9hg1roz.png)



- **Allocation**: Memory allocation refers to reserving a portion of the computer's memory to store data. In JavaScript, this is usually done when you create variables, objects, or arrays.

   ```javascript
   let num = 42; // Allocating memory for a number
   let arr = [1, 2, 3]; // Allocating memory for an array
   ```

- **Usage**: Once memory is allocated, it can be used to store data and perform operations. Proper memory usage ensures optimal performance.

   ```javascript
   let bigArray = new Array(1000000); // Using memory to store a large array
   for (let i = 0; i < bigArray.length; i++) {
     bigArray[i] = i * 2; // Utilizing memory for data storage
   }
   ```

- **Release**: Memory that is no longer needed should be released to prevent memory leaks. In JavaScript, memory is automatically released when variables go out of scope.

   ```javascript
   function example() {
     let localVar = 'I will be released'; // Memory for localVar is released after the function call
     // Code utilizing localVar
   }
   ```

## 🗑️ Garbage Collection 

JavaScript uses automatic garbage collection to reclaim memory occupied by objects that are no longer reachable or needed. The most common garbage collection algorithm is the **Mark-and-Sweep** algorithm:

1. **Mark**: The garbage collector marks all objects that are reachable from the root (global objects, local variables, etc.).

2. **Sweep**: It then sweeps through the memory, deallocating memory occupied by objects not marked as reachable.

```javascript
let obj1 = { ref: null };
let obj2 = { ref: null };
obj1.ref = obj2;
obj2.ref = obj1;
// Even though obj1 and obj2 reference each other, they will be marked for garbage collection if not reachable from the root.
```

## 💥 Memory Leaks

Memory leaks occur when memory that is no longer needed is not released, causing the application's memory usage to grow over time.

1. **Accidental Global Variables**: Variables that should have local scope become global, preventing them from being garbage collected.

2. **Closures**: Closures that retain references to outer variables even after they are no longer needed.

3. **Unused Event Listeners**: Forgetting to remove event listeners can keep objects in memory.

```javascript
// Example of a memory leak due to a closure
function setupCounter() {
  let count = 0;
  setInterval(() => {
    console.log(count++);
  }, 1000);
}
// The closure in setInterval retains a reference to the 'count' variable, preventing it from being garbage collected.
```

## Example

Consider a scenario where a web application dynamically adds and removes elements from the DOM without properly cleaning up

```javascript
const container = document.getElementById('container');

function addElement() {
  const element = document.createElement('div');
  container.appendChild(element);
}

function removeElements() {
  container.innerHTML = ''; // Elements are removed from the DOM, but references may still exist
}

// Calling addElement multiple times
addElement();
addElement();

removeElements(); // Elements are removed from the DOM, but references remain
```

**Prevention**: Remove all event listeners, references, and clean up after dynamically added elements before removing them from the DOM.