Object.create()

Creates a new object with the given prototype.

Returns
A new object.
Changes the original
No
On this page

Example

#
JavaScript
const hero = {
  greet() {
    return `Hi, I'm ${this.name}`
  }
}

const noah = Object.create(hero)
noah.name = 'Noah'

console.log(noah.greet())
console.log(Object.keys(noah))
console.log(Object.getPrototypeOf(noah) === hero)
Console
Hi, I'm Noah
['name']
true

Definition and usage

#

The Object.create(proto) method creates an empty object whose prototype is the given object. The new object inherits all its properties and methods, even though it doesn’t contain them itself.

It’s the basic inheritance mechanism in JavaScript, the one classes are built on too. In everyday code, the class syntax is used more often, but Object.create() helps you understand how the prototype chain works.

Calling Object.create(null) creates an object with no prototype at all. Such a "clean dictionary" has no inherited keys like toString, which can be handy when storing arbitrary data.

Syntax

#
Syntax
Object.create(proto)
Object.create(proto, propertiesObject)

Parameters

#
  • proto

    object or null

    The prototype of the new object.
  • propertiesObject

    optional

    Property descriptors to define right away.

More examples

#
An object with no prototype
JavaScript
const dictionary = Object.create(null)
dictionary.toString = 'just a key'

console.log(dictionary.toString)
console.log('hasOwnProperty' in dictionary)
Console
just a key
false

Browser support

#

Widely available

Works in all modern browsers, phones included. You can use it without worry.

  • Chrome
  • Edge
  • Firefox
  • Safari

Good practices

#
  • In new code, the class syntax is usually more convenient for inheritance.
  • For dictionaries with arbitrary keys, Map is often a better fit.

Related entries

#

Spotted a mistake or missing an example? Write to us.