Categories
interview

Shallow copy vs Deep copy

// Shallow Copy.
const obj = {
  a: 1,
  b: 2,
  c: 3,
  d: {
    f: 4,
  },
};

const testObj = {
  ...obj // Similar to Object.assign()
};
testObj.d.f = 5; // This modified the original object.

console.log(obj.d);
// {
//    f: 4,
//  }

const newTestObj = {
  ...obj,
  d: {
    ...obj.d
  },
};

// Deep Copy.
const deepCopy = (inpObj) => {
  const obj = {};
  for (const [key, val] of Object.entries(inpObj)) {
    obj[key] = typeof val === 'object' ? deepCopy(val) : val;
  }
  return obj;
};

console.log(deepCopy(obj));
// {
//  a: 1,
//  b: 2,
//  c: 3,
//  d: {
//    f: 5
//   }
//  }

Demo