Skip to content
jshacks.dev
Functions

Implement Object.create From Scratch in JavaScript

Implement Object.create from scratch in JavaScript with a constructor trick and with setPrototypeOf, then add property descriptors and the null prototype case.

7 min read
Summarize in AI
Flat illustration of items passing through a chain of collection methods, with the JavaScript, Node.js, Vite, npm and TypeScript logos.

Object.create(proto, descriptors) makes a new empty object whose prototype is proto, and optionally defines properties on it in the same call. Before ES5, there was no such function, and the way to get one was a short trick with a temporary constructor, which is the classic interview answer. This post implements Object.create on Node.js 24 in three ways: the historical constructor trick, the version built on Object.setPrototypeOf, and a full version with property descriptors and the null prototype that matches the real function. Each step has code and its output, followed by the tests and the explanation of what to say. The related question about new is in implementing the new operator.

What the function does

Object.create(proto) returns an object o where Object.getPrototypeOf(o) === proto. The new object has no own properties, and property lookups that miss on o continue on proto. The argument must be an object or null, and anything else throws a TypeError.

JavaScript
const animal = {
  speak() {
    return `${this.name} makes a sound`;
  },
};

const dog = Object.create(animal);
dog.name = "Rex";

console.log(dog.speak());
console.log(Object.keys(dog), Object.getPrototypeOf(dog) === animal);
console.log(animal.isPrototypeOf(dog), "speak" in dog, dog.hasOwnProperty("speak"));
Text
Rex makes a sound
[ 'name' ] true
true true false

dog has one own property, name. The method speak is found through the prototype, so "speak" in dog is true and hasOwnProperty is false. In the method, this is dog, because it was called on dog, which is why the name comes out right.

The constructor trick

An ordinary function call with new creates an object whose prototype is the function's prototype property. So a temporary constructor with prototype set to the wanted object gives the result.

JavaScript
function createViaConstructor(proto) {
  function Temp() {}

  Temp.prototype = proto;

  return new Temp();
}

const cat = createViaConstructor(animal);
cat.name = "Tom";

console.log(cat.speak());
console.log(Object.getPrototypeOf(cat) === animal);
console.log(cat.constructor === Object);
Text
Tom makes a sound
true
true

This is the answer from the days of ES3, and it is still worth knowing. The function Temp is never called with arguments and exists only to carry the prototype. The third line points at a side effect: cat.constructor comes from the prototype chain, animal has no own constructor, so lookup reaches Object.prototype.constructor, which is Object. That matches Object.create, since the real function does not add a constructor either.

The trick has two limits. It cannot create an object with a null prototype, because setting Temp.prototype = null makes new fall back to Object.prototype, as described for the new operator. And it needs a check for the argument, since a primitive for Temp.prototype also falls back silently.

JavaScript
function Fallback() {}

Fallback.prototype = null;

const surprise = new Fallback();

console.log(Object.getPrototypeOf(surprise) === Object.prototype);
console.log(Object.getPrototypeOf(Object.create(null)));
Text
true
null

The real function can return an object that has no prototype at all, which is useful as a dictionary with no inherited keys like toString or constructor.

Using setPrototypeOf

Modern code can create an empty object and set its prototype directly.

JavaScript
function createViaSetPrototype(proto) {
  if (proto !== null && typeof proto !== "object" && typeof proto !== "function") {
    throw new TypeError(`Object prototype may only be an Object or null: ${String(proto)}`);
  }

  const instance = {};

  Object.setPrototypeOf(instance, proto);

  return instance;
}

const bare = createViaSetPrototype(null);

console.log(Object.getPrototypeOf(bare), "toString" in bare);

try {
  createViaSetPrototype(5);
} catch (error) {
  console.log(error.name);
}
Text
null false
TypeError

This handles null, because Object.setPrototypeOf(obj, null) is allowed, and the explicit check for the argument gives the same error type as the built-in. The cost is performance: changing the prototype of an existing object is slow in engines, which is why the documentation of Object.setPrototypeOf warns against it in hot code. The real Object.create sets the prototype at creation time, which engines optimize. An implementation of create in terms of setPrototypeOf is correct and instructive, and it is not as fast.

The second argument: property descriptors

Object.create(proto, descriptors) accepts an object whose keys are property names and whose values are property descriptors, the same shape as the second argument of Object.defineProperties.

JavaScript
const person = Object.create(
  { kind: "human" },
  {
    name: { value: "Ana", enumerable: true },
    id: { value: 7 },
    age: {
      get() {
        return 30;
      },
      enumerable: true,
    },
  },
);

console.log(Object.keys(person));
console.log(person.id, person.age, person.kind);
Text
[ 'name', 'age' ]
7 30 human

A descriptor defaults every flag to false: writable, enumerable and configurable. So id is hidden from Object.keys and cannot be changed, and name is visible but also read-only, since only enumerable was set. Assigning to a read-only property is silently ignored in sloppy mode and throws in strict mode. These samples are ES modules, which are always strict.

JavaScript
for (const key of ["id", "name"]) {
  try {
    person[key] = "changed";
  } catch (error) {
    console.log(key, error.name);
  }
}

console.log(person.id, person.name);
Text
id TypeError
name TypeError
7 Ana

Both properties were defined without writable: true, so assignment throws a TypeError and the values are unchanged. This is the behavior of descriptors that people forget when they first use them.

The complete function

A full version combines the creation, the checks and the descriptors.

JavaScript
function objectCreate(proto, descriptors) {
  if (proto !== null && typeof proto !== "object" && typeof proto !== "function") {
    throw new TypeError(`Object prototype may only be an Object or null: ${String(proto)}`);
  }

  function Temp() {}

  let instance;

  if (proto === null) {
    instance = Object.setPrototypeOf({}, null);
  } else {
    Temp.prototype = proto;
    instance = new Temp();
  }

  if (descriptors !== undefined) {
    Object.defineProperties(instance, descriptors);
  }

  return instance;
}

const created = objectCreate(animal, { name: { value: "Mia", enumerable: true } });
const dict = objectCreate(null, { a: { value: 1, enumerable: true } });

console.log(created.speak(), Object.keys(created));
console.log(dict, Object.getPrototypeOf(dict));

try {
  objectCreate("text");
} catch (error) {
  console.log(error.message);
}
Text
Mia makes a sound [ 'name' ]
[Object: null prototype] { a: 1 } null
Object prototype may only be an Object or null: text

The null case is the only one that needs setPrototypeOf, while every other call uses the creation-time trick. Object.defineProperties handles the descriptors and throws the right errors for malformed ones. Node.js prints an object without a prototype as [Object: null prototype] { a: 1 }, which is a handy visual marker.

Prototypal inheritance with create

The classic use is setting up inheritance between constructor functions.

JavaScript
function Shape(name) {
  this.name = name;
}

Shape.prototype.describe = function () {
  return `shape ${this.name}`;
};

function Circle(radius) {
  Shape.call(this, "circle");
  this.radius = radius;
}

Circle.prototype = objectCreate(Shape.prototype, {
  constructor: { value: Circle, writable: true, configurable: true },
});

Circle.prototype.area = function () {
  return Math.round(Math.PI * this.radius ** 2);
};

const circle = new Circle(2);

console.log(circle.describe(), circle.area());
console.log(circle instanceof Shape, circle.constructor === Circle);
Text
shape circle 13
true true

Circle.prototype inherits from Shape.prototype without calling Shape, which Circle.prototype = new Shape() would do wrongly, running a constructor with no arguments to build a prototype. Setting constructor back is needed because replacing the prototype loses it. The area is pi * 4, about 12.566, which rounds to 13. Classes with extends do all of this for you, and this is what they compile down to.

Tests

JavaScript
import test from "node:test";
import assert from "node:assert/strict";

test("objectCreate links the prototype", () => {
  const proto = { hello: () => "hi" };
  const child = objectCreate(proto);

  assert.equal(Object.getPrototypeOf(child), proto);
  assert.equal(child.hello(), "hi");
  assert.deepEqual(Object.keys(child), []);
});

test("objectCreate supports null and descriptors", () => {
  const bare = objectCreate(null);

  assert.equal(Object.getPrototypeOf(bare), null);
  assert.equal("toString" in bare, false);

  const withValue = objectCreate({}, { x: { value: 1, enumerable: true } });

  assert.deepEqual(Object.keys(withValue), ["x"]);
});
Text
ℹ tests 2
ℹ pass 2
ℹ fail 0

Dictionaries and the __proto__ problem

The most practical use of Object.create(null) is a lookup table keyed by arbitrary strings. A normal object inherits from Object.prototype, so a key such as "constructor" or "toString" already exists before you add anything, and a check like if (table[word]) gives a wrong answer for those words. Counting words in a text with a plain {} is the classic example: the word "constructor" appears to have been seen already, and its count becomes a string such as function Object() { [native code] }1.

An object with no prototype has no such inherited keys, so every key you read is one you wrote. It also avoids the setter behind __proto__: assigning table.__proto__ = value on an ordinary object changes its prototype instead of creating a key, which is the basis of prototype pollution bugs when the key comes from user input. A Map solves the same problem with a cleaner API, and Object.create(null) is the choice when you need a plain object for JSON-like data or for passing to code that expects one.

The trade-off is that such an object lacks the methods you may expect. table.hasOwnProperty("a") throws a TypeError because the method does not exist, so use Object.hasOwn(table, "a"), "a" in table or Object.keys(table) instead.

How to present it

Begin with the contract: the new object's prototype is the argument, and the object starts empty. Then give the temporary constructor answer, because it is the one that most people expect, and say that it fails for null. Offer Object.setPrototypeOf as the modern shortcut and mention its cost. Finally, add the descriptors argument and describe the false defaults, which is the part that makes a complete answer.

If asked when you would use Object.create today, give two examples: dictionaries without inherited keys, using Object.create(null), and inheritance between plain objects without classes. For most application code, classes and object literals are clearer.

Taggedinterview
Share

Keep reading

Flat illustration of two options weighed side by side, with the JavaScript, Vite and Node.js logos.
Functions

Classes vs Factory Functions

Classes vs factory functions in JavaScript compared on private state, this, instanceof, inheritance, memory, JSON and testing, with exact output.

7 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.