Scriptdrill

Level 4: Data shaping Exercise 57 of 76 Free

Deep clone

A JavaScript exercise from Scriptdrill. Solve it with a code editor in your browser that runs your function against example and hidden tests, and it is checked the moment you submit.

The task

Return a deep copy of `value`, written by hand rather than with `structuredClone`. `value` is made of plain objects, arrays, Dates, strings, numbers (including `NaN`), booleans, `null` and `undefined`, nested to any depth, with no cycles. Every object, array and Date in the copy must be a new instance with the same contents, so changing the copy never changes the original. Primitives and `null` are returned as they are. Keys whose value is `undefined` are kept.

What this exercise teaches

Handling arrays, Dates and objects as separate cases is what keeps their types: a JSON round trip turns Dates into strings and drops undefined and NaN, and a spread copies only the top level, so nested objects are still shared with the original.

A hint if you get stuck

Recurse: `Array.isArray` for arrays (map over the items), `instanceof Date` for Dates (`new Date(value.getTime())`), `typeof value === "object"` for plain objects (copy each key), and return anything else unchanged.

Try it now, free, no account needed

Every exercise on Scriptdrill is free to try. Open it on the practice page, solve it, and get instant feedback with a hint. The worked solution opens once you solve it or after two tries.

Open this exercise

More exercises in Data shaping