Shallow vs Deep Copy

Shallow vs Deep Copy

Deep Copy methods

  1. JSON.parse(JSON.stringify())

  2. Service Workers postMessage() onmessage

  3. History API history.pushState(obj, title) history.state

  4. Notification API new Notification("title", {data: obj} ).data

  5. Build a custom recursive function

  6. Deep Cloning Objects - The modern way

//only contains primitive types
const shallowArray = ["false", 123, "pedbad", null, undefined];

//contains both primitive and object types
const deepArray = [
   false,
   123,
   "pedbad",
   ["Alpha", "Beta", "Delta"],
   { firstName: "John", lastName: "Doe" }
];

const deepObj = {
  coins: ["xrp", "bitcoin", "xlm", "kava"],
  exchanges: ["Binance", "Coinbase", "Bitrue"],
  altSeason: false,
  fomo: 5
};

const newObj = { ...deepObj };
newObj.exchanges[0] = 'UniSwap'; //changed inside ref.
newObj.coins = ['etheriunm', 'dent']; //new ref
console.log(newObj, deepObj);


let otherObj = JSON.parse(JSON.stringify(deepObj));
otherObj.exchanges[0] = 'UniSwap'; 
console.log(otherObj, deepObj);

Shallow Copy Method examples

  1. arr1.slice(0)

  2. [].concat(arr1)

  3. Spread Operator

  4. Object.create({}, obj)

  5. Object.assign({}, obj)

  6. Array.from(arr1)

let s = "steve";
let g = s;
s = "new value";
console.log(s, g);

let arr = Array.from(shallowArr);
//let arr1 = [...shallowArr];
shallowArr[0] = 456;
//console.log(arr, shallowArr);

Deep Cloning Objects - The modern way

There's now a native way in JavaScript to do deep copies of objects.

The structuredClone function is now built into the JavaScript runtime:

const myDeepCopy = structuredClone(myOriginal);

Great article here:
Deep-copying in JavaScript using structuredClone