All questions

Object.create

Premium

Object.create

Object.create makes a brand-new object with a prototype you choose — the most direct way to set up inheritance in JavaScript. Give it an object and the new object inherits from it; give it null and you get a truly empty object with no prototype at all (not even Object.prototype).

Implement objectCreate(proto, propertiesObject). Return a new object whose [[Prototype]] is proto. If propertiesObject is provided, define those own properties from their descriptors, like Object.defineProperties. Throw a TypeError if proto is a non-null primitive.

Signature

function objectCreate(proto, propertiesObject) {
  // new object inheriting from `proto`, with optional own descriptor props.
}

Examples

const animal = { speak() { return 'noise'; } };
const dog = objectCreate(animal);
dog.speak();                     // 'noise' — inherited
Object.getPrototypeOf(dog) === animal; // true
const bare = objectCreate(null);         // no prototype at all
bare.toString;                            // undefined
objectCreate(null, { x: { value: 1, enumerable: true } }); // { x: 1 }

Notes

  • Sets the prototypeObject.getPrototypeOf(result) is exactly proto.
  • Inherits, doesn't copy — the new object has no own properties from proto; it looks them up the chain.
  • null prototype — a "dictionary" object with none of Object.prototype's methods (toString, hasOwnProperty, …).
  • DescriptorspropertiesObject maps names to descriptors (value/writable/enumerable/configurable, or get/set); apply them as own properties.
  • Invalid proto — a number, string, boolean, etc. throws a TypeError; only an object or null is allowed.

Unlock the solution & editor

  • Runnable editor + tests

    Solve in the browser with instant Jest feedback.

  • Detailed solutions

    Walkthroughs, edge cases, and complexity notes.

  • Multi-framework variants

    React, Vue, Vanilla, Angular — same question, different stacks.

Upgrade to Premium