Shallow copy Vs Deep copy in Javascript

Arun Rajeevan
Jul 13, 2019 · 1 min read

Shallow Copying Objects

An object is said to be shallow copied when the source top-level properties are copied without any reference and there exists a source property whose value is an object and is copied as a reference. If the source value is a reference to an object, it only copies that reference value to the target object.

A shallow copy will duplicate the top-level properties, but the nested object is shared between the original(source) and the copy(target).

Example: Using Object.assign() method

The Object.assign() method is used to copy the values of all enumerable own properties from one or more source objects to a target object.

Deep copy of object

A deep copy will duplicate every object it encounters. The copy and the original object will not share anything, so it will be a copy of the original.

Example:Using JSON.parse(JSON.stringify(object));

Another Way to Deep clone

function cloneObject(obj) {
var clone = {};
for(var i in obj) {
if(obj[i] != null && typeof(obj[i])=="object")
clone[i] = cloneObject(obj[i]);
clone[i] = obj[i];
return clone;

Arun Rajeevan

Written by

Only a good tester can be the best programmer.

More From Medium

More from Arun Rajeevan


Also tagged JavaScript

Related reads

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade