Implement a deep clone function for a JavaScript object.

Code Playground
JavaScript (V8)
Loading...
Console Output
// Output will appear here...
// For React: ReactDOM.createRoot(rootElement).render(<App />);
Recommended Answer

Logic/Approach:

A deep clone must create new copies of all nested objects and arrays.

1. Handle primitives, which are copied by value.

2. Create a new empty object or array.

3. Iterate over the keys/elements of the input.

4. Recursively call the clone function on each value and assign it to the new object/array.

5. A more robust solution should handle circular references (using a Map to track visited objects).

Simple Recursive Example (without circular reference handling):

function deepClone(obj) {
  if (obj === null || typeof obj !== 'object') {
    return obj;
  }

  // Handle Arrays
  if (Array.isArray(obj)) {
    const clonedArray = [];
    for (let i = 0; i < obj.length; i++) {
      clonedArray[i] = deepClone(obj[i]);
    }
    return clonedArray;
  }

  // Handle Objects
  const clonedObj = {};
  for (const key in obj) {
    if (Object.prototype.hasOwnProperty.call(obj, key)) {
      clonedObj[key] = deepClone(obj[key]);
    }
  }
  return clonedObj;
}

const original = { a: 1, b: { c: 2 } };
const cloned = deepClone(original);
cloned.b.c = 99;

console.log(original.b.c); // 2 (original is unchanged)
console.log(cloned.b.c);   // 99