Shallow Copy vs. Deep Copy in Javascript

Jenish Dabhi - Mar 18 - - Dev Community

JavaScript is a high-level, dynamically typed client-side scripting language.

  • Shallow Copy : In JavaScript, a shallow copy refers to creating a new object or array that has an exact copy of the top-level elements of the original object or array.In simple words, a reference variable mainly stores the address of the object which is pointing to the original object or array.

A shallow copy can be achieved using the spread operator (…) or using Object.assign():

const originalObject = { name: 'John', age: 22, hobbies: ['reading', 'painting'] };

// Shallow copy using Object.assign()
const copiedObject = Object.assign({}, originalObject);

// Modifying the copiedObject
copiedObject.name = 'Johnny';
copiedObject.hobbies.push('coding');

console.log(originalObject); // { name: 'John', age: 22, hobbies: ['reading', 'painting', 'coding'] }
console.log(copiedObject); // { name: 'Johnny', age: 22, hobbies: ['reading', 'painting', 'coding'] }
Enter fullscreen mode Exit fullscreen mode
  • Deep Copy : In JavaScript, a deep copy refers to creating a new object or array that is completely independent of the original object or array. It means that all levels of the object or array, including nested objects or arrays, are duplicated, and changes made to the copy will not affect the original.

A deep copy can be achieved using JSON.parse() + JSON.stringify()

const originalObject = { name: 'John', age: 22, hobbies: ['reading', 'painting'] };

// Deep copy using JSON.stringify() and JSON.parse()
const copiedObject = JSON.parse(JSON.stringify(originalObject));

// Modifying the copiedObject
copiedObject.name = 'Johnny';
copiedObject.hobbies.push('cooking');

console.log(originalObject); // { name: 'John', age: 22, hobbies: ['reading', 'painting'] }
console.log(copiedObject); // { name: 'Johnny', age: 22, hobbies: ['reading', 'painting', 'cooking'] }

Enter fullscreen mode Exit fullscreen mode

Shallow Copy vs Deep copy

Shallow Copy

  • Shallow copy creates a new object and copies the references of the original object's elements into the new object.
  • The new object references the same memory locations as the original object for its elements.
  • If any changes are made to the shared elements in the new or original object, the changes will be reflected in both.

Deep copy

  • Deep copy creates a new object and duplicates all the elements of the original object, including any nested objects or arrays.
  • The new object has its own memory locations for all its elements, ensuring that changes made to the copy do not affect the original.

Happy coding!

. . .
Terabox Video Player