Hidden classes
- Node.js course
- Expert
- Lesson 3/47
- 5 min
Learn V8 hidden classes and inline cache.
Hidden classes
V8 assigns each object a hidden class that summarizes its structure (which properties, in which order). Objects with the same layout share the same hidden class; this speeds up property access.
As you add properties V8 transitions to a new hidden class. Example: first {} (empty), then {x: 1} (x added), then {x: 1, y: 2} (y added). The transition path: root -> x -> y. Objects that add properties in the same order share the path; different orders lead to different hidden classes. This is why adding all properties in the same order in constructors improves performance.
The transition path
We can model an object's hidden class transition path with a function. buildTransitions(['x', 'y']) returns 'root -> x -> y'. This helps you grasp V8's internals with a simple string.
The function starts with 'root' and appends ' -> ' plus the property name for each property. Example: let path = 'root'; for (const p of props) { path += ' -> ' + p; }. This models V8's transition mechanism. In real V8 each transition creates a hidden class object; here we just visualize the path as a string. This clarifies why property order matters.
Practice Write the transition path function
Write function buildTransitions(props). Start with let path = 'root'. Append each property with for (const p of props) { path += ' -> ' + p; }. Return with return path. Print console.log(buildTransitions(['x', 'y'])).
Starter code
// Write a buildTransitions function
// Start from 'root', append ' -> name' for each property
// Call with ['x', 'y'] and print
// write hereSample solution
function buildTransitions(props) {
let path = 'root';
for (const p of props) {
path += ' -> ' + p;
}
return path;
}
console.log(buildTransitions(['x', 'y']));Expected output
root -> x -> y
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match each concept to its description
| Term | Meaning |
|---|---|
Hidden class |
Summarizes an object's layout |
Transition |
Move to a new hidden class |
root |
Hidden class of an empty object |
Same order |
Shared hidden class |
2 Why do two objects not share a hidden class?
const a = {}; a.x = 1; a.y = 2;
const b = {}; b.y = 2; b.x = 1;- The names differ
- The values differ
- The property insertion order differs Correct answer
- Both are empty
Explanation: a adds x then y; b adds y then x. Different order means different hidden class.
3 Complete the for loop
for (const p of ____) { path += ' -> ' + p; }
for (const p of props) { path += ' -> ' + p; }
Explanation: The loop iterates over the props array.