0
0
JavascriptHow-ToBeginner · 3 min read

How to Use Object.create in JavaScript: Syntax and Examples

Use Object.create(proto) to create a new object with proto as its prototype. This method lets you set up inheritance easily by linking the new object to an existing one without calling a constructor.
📐

Syntax

The syntax for Object.create is:

  • proto: The object which should be the prototype of the newly created object.
  • propertiesObject (optional): An object containing property descriptors to add to the new object.

This method returns a new object linked to proto.

javascript
Object.create(proto, propertiesObject);
💻

Example

This example shows how to create a new object with Object.create that inherits from another object and adds its own property.

javascript
const animal = {
  eats: true,
  walk() {
    return "Animal walks";
  }
};

const rabbit = Object.create(animal);
rabbit.jumps = true;

console.log(rabbit.eats);      // true (inherited)
console.log(rabbit.jumps);    // true (own property)
console.log(rabbit.walk());   // "Animal walks" (inherited method)
Output
true true Animal walks
⚠️

Common Pitfalls

Common mistakes when using Object.create include:

  • Passing null or a non-object as the prototype, which can cause errors or unexpected behavior.
  • Expecting the new object to have its own properties from the prototype (it only inherits them).
  • Not using property descriptors correctly when adding properties in the second argument.

Example of a wrong and right way to add properties:

javascript
// Wrong: Adding properties directly without descriptors
const obj1 = Object.create({}, {
  name: 'John' // This is incorrect
});

// Right: Using property descriptors
const obj2 = Object.create({}, {
  name: {
    value: 'John',
    writable: true,
    enumerable: true,
    configurable: true
  }
});

console.log(obj2.name); // John
Output
John
📊

Quick Reference

ParameterDescription
protoObject to be used as the prototype of the new object
propertiesObjectOptional object with property descriptors to add to the new object
Return valueA new object linked to proto

Key Takeaways

Object.create(proto) creates a new object with proto as its prototype.
Use the second argument to add properties with descriptors safely.
The new object inherits properties but does not copy them.
Passing null as proto creates an object with no prototype.
Avoid adding properties without descriptors in the second argument.