Skip to content

Shallow copy vs Deep copy JavaScript

  • by

In JavaScript, shallow copy and deep copy are two different approaches to creating copies of objects or arrays. The key difference between them lies in how they handle nested objects or arrays.

Shallow Copy:

  • Shallow copy creates a new object or array and copies the references of the original elements to the new object or array. This means that both the original and copied objects will point to the same memory locations for nested objects or arrays.
  • It is achieved using various methods like the spread operator (...), Object.assign(), or Array.prototype.slice().
  • A shallow copy is relatively faster and requires less memory, but it can lead to unexpected behavior if the original object is modified since the changes will be reflected in the copied object as well.

Example of shallow copy in JavaScript using the spread operator:

const originalArray = [1, 2, 3];
const shallowCopy = [...originalArray];

shallowCopy.push(4);

console.log(originalArray);   // Output: [1, 2, 3]
console.log(shallowCopy);     // Output: [1, 2, 3, 4]

Deep Copy:

  • Deep copy creates a completely independent copy of an object or array, including all nested objects or arrays. It recursively copies the values of all nested elements into new memory locations.
  • It can be achieved using methods like recursion or libraries like Lodash’s cloneDeep.
  • Deep copy is slower and consumes more memory compared to shallow copy, but it ensures that any modifications made to the original object will not affect the copied object.

Example of deep copy in JavaScript using recursion:

function deepCopy(obj) {
  if (typeof obj !== 'object' || obj === null) {
    return obj;
  }

  let copy;
  if (Array.isArray(obj)) {
    copy = [];
    for (let i = 0; i < obj.length; i++) {
      copy[i] = deepCopy(obj[i]);
    }
  } else {
    copy = {};
    for (let key in obj) {
      if (obj.hasOwnProperty(key)) {
        copy[key] = deepCopy(obj[key]);
      }
    }
  }

  return copy;
}

const originalObject = {
  name: 'John',
  age: 30,
  nestedObj: {
    foo: 'bar'
  }
};

const deepCopyObject = deepCopy(originalObject);

deepCopyObject.nestedObj.foo = 'baz';

console.log(originalObject);    // Output: { name: 'John', age: 30, nestedObj: { foo: 'bar' } }
console.log(deepCopyObject);    // Output: { name: 'John', age: 30, nestedObj: { foo: 'baz' } }

Shallow copy vs Deep copy the JavaScript example

Simple example code that demonstrates both shallow copy and deep copy in JavaScript within a single code snippet:

// Original object with nested object
const originalObject = {
  name: 'John',
  age: 30,
  nestedObj: {
    foo: 'bar'
  }
};

// Shallow copy using spread operator
const shallowCopyObject = { ...originalObject };

// Deep copy using JSON methods
const deepCopyObject = JSON.parse(JSON.stringify(originalObject));

// Modifying the nested object in the copies
shallowCopyObject.nestedObj.foo = 'baz';
deepCopyObject.nestedObj.foo = 'qux';

// Printing the original and copied objects
console.log('Original Object:', originalObject);
console.log('Shallow Copy:', shallowCopyObject);
console.log('Deep Copy:', deepCopyObject);

Output:

Shallow copy vs Deep copy JavaScript

Here’s a tabular format outlining the differences between shallow copy and deep copy in JavaScript:

Shallow CopyDeep Copy
BehaviorCreates a new object/array and copies references of elementsCreates an independent copy with new memory locations for all elements
Nested ElementsChanges to the original object/array reflect in the copied objectCreates new copies of nested objects/arrays
ModificationsChanges to the original object/array do not affect the copied objectChanges to original object/array do not affect the copied object
SpeedFasterSlower
Memory ConsumptionRequires less memoryRequires more memory
MethodsSpread operator (...), Object.assign(), Array.prototype.slice(), etc.Recursion, cloneDeep (libraries like lodash)

Comment if you have any doubts or suggestions on this JS copy topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Tags:

Leave a Reply

Your email address will not be published. Required fields are marked *