16. What are the differences between shallow and deep copy?

Shallow copy means that only object is copied, but references inside it point to the same values as references in original object.

Content of objects and arrays could be shallow copied using spread operatora ....

const obj = {a: {}, b: {}}; const copyObj = {...obj}; const arr = [{}, {}]; const copyArr = [...arr]; console.info(obj === copyObj, obj.a === copyObj.a, obj.b === copyObj.b); // false, true, true console.info(arr === copyArr, arr[0] === copyArr[0], arr[1] === copyArr[1]); // false, true, true

Before spread operator introduced in ES2018, shallow copies could be done using Object.assign:

const obj = { a: 1 }; const copyObj = Object.assign({}, obj); console.info(obj === copyObj, obj.a === copyObj.a, obj.b === copyObj.b); // false, true, true

Deep copy copies all descendant values and their descendants.

There are few ways of making deep copy.

One of them is to serialize object to string, and then deserialize it back to an object:

const obj = {a: {}, b: {}}; const copyObj = JSON.parse(JSON.stringify(obj)); const arr = [{}, {}]; const copyArr = JSON.parse(JSON.stringify(arr)); console.info(obj === copyObj, obj.a === copyObj.a, obj.b === copyObj.b); // false, false, false console.info(arr === copyArr, arr[0] === copyArr[0], arr[1] === copyArr[1]); // false, false, false

This solution is fine for simple object - without prototypes, functions etc.

Another solution is to use window function structuredClone:

const obj = {a: {}, b: {}}; const copyObj = structuredClone(obj); const arr = [{}, {}]; const copyArr = structuredClone(arr); console.info(obj === copyObj, obj.a === copyObj.a, obj.b === copyObj.b); // false, false, false console.info(arr === copyArr, arr[0] === copyArr[0], arr[1] === copyArr[1]); // false, false, false
devFlipCards 2024

Do you accept cookies?

Cookies are small amounts of data saved locally on you device, which helps our website - it saves your settings like theme or language. It helps in adjusting ads and in traffic analysis. By using this site, you consent cookies usage.