Course contentsShow
← JavaScript
Lesson 1912 of 2,72340. PerformanceFree lesson

Initializing Objects Consistently

Constructor functions that always set the same properties in order produce optimal hidden classes.

Initializing Objects Consistently

What you'll learn: How creating objects with the same properties in the same order helps JavaScript engines optimize your code for speed.

The Problem with Inconsistent Initialization

When you create multiple objects that are supposed to represent the same type of thing, V8 (and other engines) perform best when those objects follow an identical pattern. If you initialize properties in different orders, add different properties, or skip properties on some instances but not others, you're creating different hidden classes for what should be the same shape of object.

This forces the engine to handle each variation separately, preventing optimizations and slowing down property access.

Always Set the Same Properties, Same Order

Think of hidden classes like assembly line blueprints. If every car coming off the line has a chassis, then an engine, then wheels installed in that exact order, the factory optimizes for that sequence. If some cars skip steps or add them in random order, the factory loses efficiency.

// ❌ Bad: inconsistent initialization
function createUser(name, age) {
  const user = {};
  user.name = name;
  if (age !== undefined) {
    user.age = age; // Sometimes present, sometimes not
  }
  return user;
}

// ✅ Good: always set the same properties
function createUser(name, age) {
  const user = {};
  user.name = name;
  user.age = age; // Always present, even if undefined
  return user;
}

Both versions work functionally, but the second creates objects with a consistent hidden class. The engine can optimize property lookups because it knows exactly where name and age live in memory for every user object.

Use Constructor Functions or Classes

Constructor functions and classes naturally enforce this consistency, making them excellent for performance:

class Point {
  constructor(x, y) {
    this.x = x;
    this.y = y;
  }
}

Every Point instance gets both properties in the same order, every time.

Key Takeaway: Initialize all objects of the same "type" with identical properties in identical order—even if some values are undefined—to create consistent hidden classes and unlock V8's optimization potential.