Objects and references12 / 19

Memory Heap: where objects are stored

How two variables access the same object in memory.

When a program creates an object { hp: 100 }, its data needs to be stored somewhere. V8 stores objects in a memory area called the heap.

Consider how an object is created and a second reference appears:

const player = { hp: 100 };
const target = player;
target.hp = 80;
// player.hp is also 80
  1. const player = { hp: 100 } creates a player object. In the interactive diagram, V8 allocates heap memory for it and stores its hp property there. The variable player receives a reference to this object.
  2. const target = player reads the value of player and assigns it to target. This copies the reference: both variables now provide access to the same object. No second object is created.
  3. target.hp = 80 follows the reference to the object and changes its hp property. The references themselves stay the same. As a result, player.hp also becomes 80.
player
target
Heap · object memory
One player object{ hp: 80 }
State after target.hp = 80. Both arrows lead to the same object.

The diagram shows the connections between the variables and the object. The engine determines the actual memory layout. Below, we will execute the example line by line: the object, references, and property values appear as execution proceeds.

Executing line by line

Interactive diagram. #1 is an illustrative object label, not a memory address.

  1. const player = { hp: 100 }; Next
  2. const target = player;
  3. target.hp = 80;

Variables

playerLine not executed yet
targetLine not executed yet

Heap

The example object has not been created yet
player.hp
—
target.hp
—

No lines have run yet. We will start by creating an object.

Executed 0 of 3
Key takeaway

The heap stores objects and their data. A variable accesses an object through a reference. Assigning its value to another variable copies the reference, not the object.

Check the primary source ↗

ECMA-262 · Object Type↗Objects and their properties. The specification does not prescribe the exact placement of objects in memory.V8 · Heap and allocation↗Managed object memory and garbage collection in V8.ECMA-262 · GetValue↗Reading a variable returns its value; for an object, this is the same object, without copying its properties.