Start learning free

LESSON 144 OF 161 · FRONTEND: INTERVIEW QUESTIONS

Deep Clone in JavaScript

Practice

In JavaScript, const b = a; doesn't copy an object: a and b are two names for the same object, a reference. The spread { ...a } makes a new object, but copies only one level, a shallow copy: the arrays and objects inside are still shared.

An example with another object:

const pen = { name: "Pen", colors: ["blue", "red"] };
const copy = { ...pen };
copy.name = "Pencil";        // pen.name is still "Pen"
copy.colors.push("green");   // pen.colors is now ["blue", "red", "green"]!

A deep clone copies every level. For an object, it makes a new object and deep-clones the value under each key: deepClone calls itself, so objects inside objects are copied at any depth. Values that aren't objects (numbers, strings, booleans, null, undefined) come back as they are. An array must stay an array, and a Date must become a new Date with the same time.

The check copies a product, changes the copy, and prints both. Part of what it must print:

copy.price = 10
copy.tags.push("sale")
copy.stock.count = 4
original: { id: 1, name: "Mug", price: 12, tags: ["kitchen", "gift"], stock: { count: 5, shelf: "A" } }
copy:     { id: 1, name: "Mug", price: 10, tags: ["kitchen", "gift", "sale"], stock: { count: 4, shelf: "A" } }
copy === mug: false, copy.tags === mug.tags: false, copy.stock === mug.stock: false

deepClone(12) returns 12
deepClone(null) returns null
deepClone({}) returns {}, deepClone([]) returns []

Your task: write deepClone(value) in solution.js, so that changing the copy never changes the original, and changing the original never changes the copy.


Assignment
Follow the Coding Tutorial to return simple values as they are, copy an object key by key with deepClone, then handle arrays and Dates.


Hint
typeof null is "object", so test for null on its own. A Date has no keys of its own: copied key by key, it becomes {}, so it needs its own check before the object part.


STEP 1 OF 7
    Ctrl + Enter to check

    Fe Deep Clone in JavaScript

    Keep going with JavaScript1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free