← Back to Engine

Memory Layout: Stack vs Heap


JavaScript manages memory allocation automatically, split between two primary memory architectures: the Stack and the Heap.

1. The Call Stack (Primitives & Pointers)

The Stack is a high-speed LIFO (Last In, First Out) structure. It holds static data whose size is known at compile time:

  • Primitive Values: number, string, boolean, null, undefined, symbol, bigint.
  • Memory Pointers: 64-bit reference addresses pointing to dynamic objects in the Heap.

2. The Heap (Dynamic Allocation)

The Heap is an unorganized memory pool storing complex, dynamic data structures:

  • Objects, Arrays, and Functions are stored on the Heap.
  • Copying an object variable (e.g., let b = a) only copies the Stack pointer, so both variables reference the exact same memory allocation on the Heap!

3. Critical Takeaways: Shallow vs Deep Copy

Methods like Object.assign() or the spread operator {...obj} only perform a shallow copy. Top-level primitives are duplicated, but nested objects still share memory addresses on the Heap. True deep cloning requires recursively creating new Heap allocations for all nested structures.


Memory Layout Diagram

The Challenge: Deep Memory Cloning

Implement a function deepClone(obj) that recursively clones an input object (including nested objects and arrays) so that no Heap object references are shared between the original and the clone.