Javascript Fundamentals · Interview Challenges

Deep clone a value

deep clone

Deep clone a value

You copy an object with { ...original } so you can edit it without touching the original. Then you change copy.address.city and find original.address.city has changed too. The spread copied the top level, but the nested address object is still the same reference.

A deep clone copies a value all the way down, so the copy shares no references with the original. Change the copy and the original is untouched.

The fix is to walk the value recursively. When a property is itself an object or array, clone that too:

function deepClone(value) {
  if (Array.isArray(value)) {
    return value.map(deepClone);
  }
  if (value !== null && typeof value === 'object') {
    return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, deepClone(item)]));
  }
  return value;
}

Primitives (string, number, boolean, null, undefined) are returned as-is, because copying them copies the value itself. Arrays are mapped element-by-element. Plain objects are rebuilt key-by-key, recursing into each value so every level is fresh.

Export deepClone from index.js. Your job is to make the returned copy independent of the original at every depth.

Challenge

You spread an object to get an independent copy, then edit a nested property and watch the original change with it — the nested objects were shared. Export a deepClone function from index.js to copy every level.

deepClone takes any value and returns a copy that shares no references with the original. Nested objects and arrays must be copied too, not reused. After cloning, mutating a nested property on the copy must leave the original unchanged.

index.js
export function deepClone(value) {
  return { ...value };
}

export function render(mount) {
  const original = { name: 'Ada', skills: ['js', 'ts'] };
  const copy = deepClone(original);
  copy.skills.push('go');

  const originalLine = document.createElement('p');
  originalLine.textContent = `Original: ${original.skills.join(', ')}`;
  const copyLine = document.createElement('p');
  copyLine.textContent = `Copy: ${copy.skills.join(', ')}`;
  mount.append(originalLine, copyLine);
}

No test run yet

The Test is hidden. Run it to check the Challenge — you only see the result, never the test source.