Facebook Pixel

Does Object.assign do a deep copy in JavaScript?

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.

Verify This Answer

Cross-check this information using these trusted sources:

More FAQs in Object.create vs new vs Object.assign in JavaScript

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.

Still have questions?

Browse all our FAQs or reach out to our support team

Want to upskill yourself?

Our courses are taking a Coffee break, but your curiosity shouldn't. Stay engaged with namastedev linkedin, youtube, discord and other resources while you wait.

0