Medium

Deep Cloning Objects in JavaScript

Description

In JavaScript, creating a copy of an object can be tricky because simply assigning an object to a new variable or using shallow cloning methods like Object.assign() or the spread operator (...) only creates a shallow copy.

This means that nested objects within the original object are still referenced, not copied.

In this challenge, you will create a function that performs a deep clone of an object.

A deep clone ensures that all nested objects and arrays are also copied, so changes to the cloned object do not affect the original object.

Example Object Structure:

const original = {
name: "Alice",
details: {
age: 25,
address: {
city: "New York",
zipCode: "10001"
}
}
};

Your task is to complete the function deepClone, which should take an object as a parameter and return a deep clone of that object.

Example Usage:

const original = {
name: "Alice",
details: {
age: 25,
address: {
city: "New York",
zipCode: "10001"
}
}
};
const cloned = deepClone(original);
console.log(cloned); // Expected output: A deep clone of the `original` object
cloned.details.age = 30; console.log(original.details.age); // Should still be 25

Constraints:

  • The input will always be a valid object.
  • The function should return a deep clone of the input object, including all nested objects and arrays.
  • The cloned object should be completely independent of the original object.

window code 2Test Cases

Input:

{
  "name": "Alice",
  "details": {
    "age": 25,
    "address": {
      "city": "New York",
      "zipCode": "10001"
    }
  }
}

Expected Output:

{
  "name": "Alice",
  "details": {
    "age": 25,
    "address": {
      "city": "New York",
      "zipCode": "10001"
    }
  }
}