Data Mechanics

JavaScript data types are physically divided into two categories based on where they are stored in the architecture.

A. Primitives

These are immutable data types that fit directly inside a single Stack Memory Slot.

  • Storage: The value lives inside the Stack Frame.
  • Access: Direct. The variable name stored in the variable environment or lexical environment points to the slot, and the slot contains the actual bits.
  • Immutability : Primitives are immutable because their memory slot is a fixed-size container for a specific bit pattern. We cannot modify individual bits within that slot; to change the value, the engine must overwrite the entire slot with a completely new set of bytes.
  • Types: number, string, boolean, undefined, null, symbol, bigint.

B. The Object Family

These are mutable collections that live in the Heap.

  • Storage Split:
    1. The Stack: Holds a Reference.
    2. The Heap: Holds the actual Payload (The key-value pairs).
  • Access: Indirect. The engine reads the address from the Stack, then jumps to that address in the Heap to find the data.
  • Types: Object, Array, Function, Date, Map, Set, WeakMap.

Array Architecture

In lower-level languages (C, Java), an Array is a contiguous block of reserved memory. In JavaScript, it is not.

A. Arrays are Objects

Physically, a JavaScript Array is just a specialized Object in the Heap.

  • Index as Key: It functions exactly like a standard object, where the Index is the Key and the Element is the Value.
  • Internal Storage: When we write arr[0] = "A", the engine treats it almost exactly like obj["0"] = "A". The indices are treated as string keys internally.
  • The Length: The main difference between an Array and a regular Object is that an Array maintains a special auto-updating length property.

B. Sparse Arrays

Because Arrays are just Objects (Key-Value maps), they don't need to allocate memory for empty slots.

Consider a scenario where we initialize an empty array and assign values only at index 0 and index 1000:

Physical Reality: The Engine does NOT reserve 1001 memory slots. It creates an Object with exactly two keys: 0 and 1000.

The Gap: Indices 1 through 999 simply do not exist in memory. They are holes. Accessing arr[50] returns undefined not because the slot is empty, but because the Key Lookup Failed (similar to accessing a missing property on an object).

Summary Table

FeaturePrimitivesObjectsArrays
Storage LocationStackHeapHeap
Variable HoldsThe ValueThe Address (Pointer)The Address (Pointer)
MutabilityImmutableMutableMutable
StructureFixed SizeDynamic GraphHash Map (Key-Value)
Lookup CostInstant1 Pointer JumpKey Hashing + Pointer Jump