JavaScriptmediumJavaScript

Deep Clone Object

Creates a completely independent copy of an object, including nested objects

01

The problem

Need to copy an object where modifications to the copy don't affect the original

02

The solution

JavaScript
function deepClone(obj) {
  if (obj === null || typeof obj !== 'object') {
    return obj;
  }
  
  if (obj instanceof Date) {
    return new Date(obj.getTime());
  }
  
  if (obj instanceof Array) {
    return obj.map(item => deepClone(item));
  }
  
  if (typeof obj === 'object') {
    const clonedObj = {};
    for (let key in obj) {
      if (obj.hasOwnProperty(key)) {
        clonedObj[key] = deepClone(obj[key]);
      }
    }
    return clonedObj;
  }
  
  return obj;
}

03

Parameters

objobject

Object to deep clone

04

Put it to work

Example
const original = {
  name: "John",
  address: {
    city: "New York",
    country: "USA"
  },
  hobbies: ["reading", "coding"]
};

const cloned = deepClone(original);
cloned.address.city = "Boston";
console.log(original.address.city); // "New York" (unchanged)