BeginnerCoder

Lesson 24 — Deep clone

Copy all the way down

A shallow copy ({ ...obj }) copies only the top level; inner objects are still shared, so changing copy.n.v also changes the original. A deep clone copies every level. Recursion makes it short: plain values are returned as they are; objects and arrays get a new container with each property deep-cloned.

typeof x !== "object" || x === null   // a plain value

Why it matters: hidden shared state is one of the hardest bugs to find.

Want it another way?
Task

In the loop, set out[k] = deepClone(x[k]), so changing the copy leaves the original alone.

Run your code — when the output matches the task, you will see a green check. Then mark the lesson complete.

← Back
Next →
Test your knowledge

A quick 3-question quiz on this lesson — instant feedback.

Enjoying this lesson? Share it.

Keep going with JavaScript Foundations

Ready for more? Optional paid resources that pick up where this lesson leaves off.

Some links on this page are affiliate links: we may earn a commission at no extra cost to you. As an Amazon Associate I earn from qualifying purchases.