3 Ways To Not Copy Objects in JavaScript (Spread, Assign & JSON)

Wings of desire

TLDR; If your object or array is of single level and contains only primitive values then you may use these methods without worry.

1. Why you should not use Object.assign()

object.assign() only does a shallow copy. Means if your object is nested. Even if your object has two levels. Object.assign won’t work.

Consider below code:

Think 🤔 of a moment, about what will be printed in the console.
.

.

.

.

.
If you think, it will print Galactus , then you’re wrong. You may check it out. It will console Thanos in the console.
Why ? Just because object.assign() does a shallow (only one level) copy.

2. Why you should not use ES6 Spread Operator to clone arrays/objects?

Let us consider below code snippet:

Take few seconds to think, what will be printed in console.
.

.

.

.

.

If you think it will console JS then you’re wrong. It’s gonna console JS always blow 🤯 my mind .Why ? Because of same reason. Spread Operator also does a shallow(one level) copy.

Now consider below code, Now I am running a map so that I can get a new array. What do you think? Will it make any difference?

.

.

.

.

.

No, The output will still be the same. JS always blow 🤯 my mind .

Why? because map us indeed returning a new array, but inside it the reference of objects are same.

How to fix it?

Only if objects inside array are single level.

3. Why you should not use JSON.stringify() to clone arrays/objects?

Consider bellow code snippet:

Take a moment, and think, what will be printed in the console?
.

.

.

.

.
If you are thinking that it will print Hello !!! then you’re wrong. It’s gonna throw an error that newObj.show() is not a function. Why?
Because once we call JSON.stringity() on any object, we simply lose any referential information the object has.

I hope, next time you use these methods, you will be aware of the consequences of using them !!!

Learn about Immutability in JavaScript and how to solve the problem which above methods are not able to do, by visiting this article.
https://rahuulmiishra.medium.com/immutability-in-javascript-892129a41497

Cheers !!!
🍻

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store