Facebook Pixel

Object.create vs new vs Object.assign in JavaScript

Three ways to create objects. Here is when to use each.

Object.create vs new vs Object.assign

Object.create(proto)

Creates a new object with the specified prototype:

const animal = { eat: () => "eating" }; const dog = Object.create(animal); dog.__proto__ === animal; // true

new Constructor

Creates an instance with the constructor's prototype:

function Person(name) { this.name = name; } const p = new Person("Kunal"); p.__proto__ === Person.prototype; // true

Object.assign(target, ...sources)

Copies properties from sources to target (shallow copy):

const defaults = { a: 1, b: 2 }; const options = Object.assign({}, defaults, { b: 3 }); // { a: 1, b: 3 } (new object, does not modify defaults)

When to Use Each

  • Object.create: when you want to set the prototype directly.
  • new: when you want to create an instance of a constructor/class.
  • Object.assign: when you want to merge or shallow-copy objects.

The Takeaway

Object.create: set the prototype directly. new: create an instance of a constructor. Object.assign: merge/copy properties (shallow). Use Object.create for prototypal inheritance, new for classes/constructors, Object.assign for merging.

Object.create(proto) creates an object with the specified prototype (no constructor call). new Constructor() calls the constructor function and sets the prototype to Constructor.prototype. Object.create is for direct prototype setting; new is for instantiation.

Copies properties from source objects to a target object (shallow copy). Object.assign({}, defaults, overrides) creates a new object with merged properties. It does not copy inherited properties, only own enumerable properties.

When you want to create an object with a specific prototype without calling a constructor. For example: const dog = Object.create(animal) creates an object that inherits from animal without running any constructor code.

No. Object.assign does a shallow copy. Nested objects are referenced, not copied. For deep copy, use structuredClone(), JSON.parse(JSON.stringify(obj)), or a library like lodash's _.cloneDeep.

Object.create(null) creates an object with no prototype (no __proto__, no toString, no hasOwnProperty). {} creates an object with Object.prototype as its prototype. Object.create(null) is useful for hash maps where you do not want any inherited properties.

Ready to master React completely?

Want to upskill yourself, crack your next interview, and get your dream job? Join our comprehensive course to dive deeper with high-quality video tutorials, solve interview questions, and a premium community.

Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.