JavaScript Course
JavaScript
/
Intermediate

Object.create()

Definition

A static method that creates a new object, using an existing object as the prototype of the newly created object.

Explain Like I'm New

If you want to create a new object that inherits from an old object, `Object.create(old)` is the cleanest, most direct way to do it. It skips constructor functions and `new` keywords entirely.

Real World Example

Creating a pure dictionary object with no built-in JavaScript methods (like `.toString`) by using `Object.create(null)` to prevent prototype pollution attacks.

Common Use Cases

  • •Prototypal inheritance without Classes
  • •Creating objects without the default `Object.prototype`

Interactive Example

const dogPrototype = {
  bark() { console.log('Woof!'); }
};

// Create a new object that inherits from dogPrototype
const myDog = Object.create(dogPrototype);
myDog.name = 'Fido';
myDog.bark(); // 'Woof!'

// Pure dictionary (No prototype)
const pureMap = Object.create(null);
// pureMap.toString(); // ERROR: pureMap.toString is not a function

Interview Questions

basic

  • What does `Object.create()` do?

intermediate

  • Why would someone use `Object.create(null)`?

advanced

  • What is the second argument of `Object.create()` used for?

Flash Cards

Question

Why use Object.create(null)?

Click to reveal answer
Answer

It creates an object with no prototype chain whatsoever. This makes it a perfectly pure dictionary/hash map. It is immune to prototype pollution because hackers cannot overwrite `Object.prototype.toString` to attack it, as it doesn't inherit from `Object`.

Question

What is the second argument?

Click to reveal answer
Answer

It allows you to define Property Descriptors for the new object, defining properties that are read-only, non-enumerable, etc.