The limits of Object.assign()

So, you have been using Object.assign to create copies of your objects right? Here’s a warning for you. Object.assign does not perform a deep copy.

Consider the following example:

Let’s say we want to create a second object for “John” who has the same age, and lives in the same city, but has a different height and lives in a different street.

We should have two independent objects right? Let’s see…

The street property also changed for paul, what happened? For primitive properties like age and height, Object.assign copied its values, but for non-primitive properties like address it copied the reference.

You’ve been warned.


There’s a better way to do this. Object.assign() accepts multiple arguments so we can “merge” multiple objects at the same time.

The last arguments takes precedence over the first ones so we end up with our desired final object:

But the good thing is that now, our object paul remains untouched.

That’s how you create a copy of an object.

Published by

David Barreto

David Barreto is a Javascript Developer with a Bachelor's degree in Electronics Engineer and a Master's degree in Systems Engineering. He is passionate about developing web apps, teaching programming, discovering new technologies and learning all about software development methodologies. He currently works at in Toronto.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.