Skip to content
Deep Clone an Object in JavaScript

Deep Clone an Object in JavaScript

Given an object, create a deep clone of it. This is a common interview question, and we are advised not to use any built-in methods to solve this problem.

🟡 Medium 🧩 Pattern – Objects

Drawbacks of other methods

  • Using the spread (…) syntax only creates a shallow copy: only level one items are cloned, but for all nested and deeper objects, only the reference is made.
  • Using JSON.stringify() and parse() will create certain problems like converting date objects to strings

structuredClone is the way ✅

The structuredClone() method of the Window interface creates a deep clone of a given value using the structured clone algorithm. — MDN

Function to Deep Clone a JS Object

function deepClone(value) {
  // Return if a primitive data type(string, int, bool) or null
  if (typeof value !== 'Object' || value === null) {
    return value;
  }

  // Return a new array by deepCloning its children (if nested)
  if (Array.isArray(value)) {
    return value.map((item) => deepClone(item));
  }

  // Return a Deep Clone an object with all its properties
  const clone = {};
  for (const key in value) {
    // Only clone properties directly owned by the object
    if (Object.prototype.hasOwnProperty.call(value, key)) {
      clone[key] = deepClone(value[key]);
    }
  }
  return clone;
}

const obj = {
  movie: 'Matrix',
  year: 1999,
  cast: ['Keanu', 'Jhon', 'Doe'],
  reviews: { postive: [4, 5, 5], negative: [3, 3, 3] },
};

const copy = deepClone(obj);
console.log(copy);

// OUTPUT
// {
//   movie: 'Matrix',
//   year: 1999,
//   cast: [ 'Keanu', 'Jhon', 'Doe' ],
//   reviews: { postive: [ 4, 5, 5 ], negative: [ 3, 3, 3 ] }
// }Code language: JavaScript (javascript)

Object.hasOwn

To verify if a property exists on the parent object and is not inherited, Object.hasOwn() can also be used. It serves the same purpose as Object.hasOwnProperty.call(value, key); however, this approach is more clear and ergonomic.

const hero = {
  name: "Peter Parker",
};

console.log(Object.hasOwn(hero, "name"));
// Expected output: true

console.log(Object.hasOwn(hero, "toString"));
// Expected output: falseCode language: JavaScript (javascript)
Back to Top