Sub topic 6
Shape Transitions and Why Property Order Matters
The previous chapter showed that V8 gives every object a hidden class, which V8 calls a map. The map describes the object's layout: which properties it has and the offset where each value lives. JavaScript lets you add properties at any time, though, so a map cannot stay fixed for an object's whole life. This chapter covers what happens when an object's shape changes. It explains how V8 records those changes as transitions, and why two objects with identical keys can still end up with different shapes.
This chapter assumes you can write constructors, classes, and object literals, and that you can run Node.js from the command line. Some examples use V8's native syntax, which needs the --allow-natives-syntax flag. A later chapter covers that tooling in detail.
What a Transition Is
When you add a property to an object, V8 doesn't edit the object's current map. Other objects may share that map, and editing it would corrupt their layouts. V8 moves the object to a different map that describes the old layout plus the new property. The link from the old map to the new one is a transition, labeled with the property name that was added.
V8 caches these transitions. The first object that goes from shape {} to shape {x} creates the new map and records an edge labeled x on the old map. Later objects that start at {} and add x follow the existing edge to the same map, so V8 creates no new map. This reuse is why objects built the same way end up sharing a hidden class.
A series of transitions from an empty object to its final shape is a transition chain. Chains that start from the same root and branch at different property names form a transition tree.
Maps M2 and M5 hold the same property names but sit at different leaves of the tree. To V8 they are different shapes.
Why Order Matters
A map records each property's offset as well as its name. In M2, x is in slot 0 and y in slot 1. In M5 the slots are swapped. Code that reads o.x from an M2 object needs a different offset from code that reads it from an M5 object. V8 therefore can't treat the two as one shape.
You can check this yourself:
// Run with: node --allow-natives-syntax order.js
function makeXY() {
const o = {};
o.x = 1;
o.y = 2;
return o;
}
function makeYX() {
const o = {};
o.y = 2;
o.x = 1;
return o;
}
console.log(%HaveSameMap(makeXY(), makeXY())); // true: same chain
console.log(%HaveSameMap(makeXY(), makeYX())); // false: different orderObject literals behave the same way. { x: 1, y: 2 } and { y: 2, x: 1 } produce different maps, even though Object.keys would list the same names for both, in different orders.
What Else Causes a Transition
Adding a property is the most common cause of a transition, but it isn't the only one. The following operations also move an object to a different map:
| Operation | Effect on shape |
|---|---|
| `o.newProp = v` | Transition to a map with one more property |
| `Object.defineProperty(o, 'k', { writable: false, value: 1 })` | Transition keyed on both the name and the attributes |
| `Object.freeze(o)` / `Object.seal(o)` | Transition to a frozen or sealed variant of the map |
| `Object.setPrototypeOf(o, p)` | New map, because the prototype is part of the map |
| Storing a double where only small integers were stored | Field representation is generalized, and the old map is deprecated |
| `delete o.someProp` | Often leaves the fast path entirely (next chapter) |
Field Representation Changes
V8 also tracks what kind of values each field holds. A field can be a small integer (Smi), a double, a heap object, or any tagged value. If every Point so far has stored Smis in x, the map records x as a Smi field. When you later store 1.5 into x, V8 doesn't create a sibling branch. It generalizes the field to a double and marks the old map as deprecated. Objects that still use the deprecated map get migrated to the new one the next time V8 touches them.
Migration keeps the transition tree from splitting into one branch per value type, but it isn't free. Code optimized for the old representation has to be thrown away. If integer and floating-point values must share a field, the cost stays small when the field holds both from the start, which avoids a mid-run change.
Constructors and Classes Build Stable Chains
Constructors and classes are the easiest way to get consistent shapes, because they run the same assignments in the same order every time. V8 also reserves in-object slots for properties set in a constructor. During the first few constructions, V8 counts how many properties instances actually receive, a process called slack tracking. It then shrinks the reserved space to fit. Properties stored in-object are faster to reach than ones that spill into a separate backing store.
Class fields are initialized in declaration order before the constructor body runs:
// Run with: node --allow-natives-syntax classes.js
class Vec {
x = 0;
y = 0;
constructor(x, y) {
this.x = x; // overwrites an existing field: no transition
this.y = y;
}
}
const v1 = new Vec(1, 2);
const v2 = new Vec(3, 4);
console.log(%HaveSameMap(v1, v2)); // trueAssigning to a property that already exists doesn't change the shape. Only adding a new one does.
Common Pitfall: Conditional Properties
The most common way code splits its shapes is by adding a property only on some paths:
// Run with: node --allow-natives-syntax conditional.js
function User(name, admin) {
this.name = name;
if (admin) {
this.isAdmin = true;
}
this.id = Math.random();
}
const u1 = new User('ana', false);
const u2 = new User('bo', true);
console.log(%HaveSameMap(u1, u2)); // false: {name, id} vs {name, isAdmin, id}The two users branch after name. They also store id at different offsets, so even a read of u.id sees two shapes. The fix is to always assign every property, in the same order, using a placeholder value when there is nothing meaningful to store:
// Run with: node --allow-natives-syntax conditional-fixed.js
function User(name, admin) {
this.name = name;
this.isAdmin = Boolean(admin);
this.id = Math.random();
}
console.log(%HaveSameMap(new User('ana', false), new User('bo', true))); // trueOther patterns that split shapes in the same way:
- Spreading or merging options objects whose keys arrive in different orders, such as
{ ...defaults, ...userOpts }whereuserOptsvaries. - Building objects from parsed JSON with inconsistent key order.
- Lazily attaching cache fields (
obj._cached = ...) to objects that are already in use. - Factory functions with several
return { ... }literals that list keys in different orders.
How Deep Can Chains Get?
Every addition extends the chain, so an object built by adding hundreds of properties one by one produces a long chain. V8 stores the property descriptors for each map in a descriptor array that maps along the same chain share, so a long chain doesn't copy descriptors at every step. V8 does set limits, though. Objects with very many properties, or properties added in patterns that look like a hash table, may be switched to dictionary mode. Code that uses objects as maps with arbitrary keys should use Map instead.
Exercises
Exercise
Two objects are created as const a = {}; a.k = 1; a.m = 2; and const b = { k: 5, m: 6 };. Ignoring literal-specific in-object slot sizing, which property of their construction decides whether their layouts match, and does the difference in values matter?
Show answer
The order in which the property names are added decides it. Both add k and then m, so both store k first and m second. The values 1/2 versus 5/6 don't matter because all are small integers with the same field representation. In practice the literal may reserve a different number of in-object slots than the empty-object path, so %HaveSameMap can still report false. That is why literals and incremental construction shouldn't be mixed for objects that hot code treats as the same type.
Exercise
A constructor runs this.a = 1; if (opts.b) this.b = opts.b; this.c = 3;. How many distinct maps can instances end up with, and how would you rewrite it so all instances share one?
Show answer
Two leaf maps: {a, c} and {a, b, c}, with c at a different offset in each. Rewrite it to always assign every field in a fixed order, for example this.a = 1; this.b = opts.b ?? null; this.c = 3;.
Exercise
Every Point has stored integers in x. You then construct one Point with x = 0.5. Does V8 create a new sibling branch in the transition tree? What happens to existing Points?
Show answer
No. V8 generalizes the x field's representation from Smi to double, creates an updated map, and deprecates the old one. Existing Points are migrated to the new map lazily, the next time V8 touches them, and optimized code that assumed Smi fields is discarded.