Ways to assign Arrays or Objects to other variables.

Abhishek Kovuri
Dec 14, 2020 · 3 min read

Assignment Operator
Most Common way to assign a variable to another variable is Assignment Operator (=). But this is one of the dangerous ways when you deal with computing the array of objects.
In the ocean of web development, we often come across many manipulations in arrays and objects, which eventually require assigning the original data and doing computation of that data in another variable without disturbing the original one, which is impossible while assigning the variable directly as it copies the reference of the original one.

Assignment Operator

It is nothing but a Copy of the original one with the same reference.
Hence, Assignment Operator is not recommended when dealing with Arrays and Objects.

This is another way in assigning Array or Objects to another variable. This method normally creates another reference for the copy of the original one.


So, here you can actually do any manipulations which don’t affect the original one.
But Object.assign() method is a shallow copy, which works the same as assignment operator if the object level is more than one.

Object.assign() for higher order objects

So here if you observe the name field in address_obj is changed after its assignment to address_obj_assign but then too it got copied to the new variable which can be dangerous at times while computation.

It is recommended for single-level Objects/Arrays but not nested objects/arrays which is quite risky when you do big computations.

Spread Operator
This is a new ES6 Feature which can be used in place of Object.assign() method. To be Specific, even spread operator is also a shallow Copy and works exactly the same as Object.assign().

Spread Operator

JSON.parse and JSON.stringify
This is often a deepCopy of the original One and copies the items recursively by creating a compound object and inserting into it.

JSON.stringify is normally a deep copy of the original one and JSON.parse normally parses the stringified version of the copy and make it as parsed Array or object.



The method discussed above is different at a different level of Objects. Preferable to the computation and manipulation, we can actually choose any one of the above methods which suit the purpose and don’t disturb the flow.

That’s it for this Blog. Thanks for Reading!!!!
If you like, give it a clap and share to your friends :)

Until the next time, Good Bye :), Happy Coding!!!

Nerd For Tech

From Confusion to Clarification