JavaScript Course
JavaScript
/
Advanced

Implement: Deep Clone Object

Definition

Write a function that recursively copies an object so that no nested objects share a memory reference with the original. Cannot use `JSON.parse` or `structuredClone`.

Explain Like I'm New

The interviewer wants to see if you can handle recursion with complex data types, specifically filtering out Arrays vs Objects vs Primitives, and handling edge cases like `null`.

Real World Example

Cloning `{ a: 1, b: { c: 2 } }`.

Common Use Cases

  • •Interview screening
  • •Understanding JS data types

Interactive Example

Loading...
Console output will appear here...

Interview Questions

basic

  • Why does `typeof null` complicate this question?

intermediate

  • Write a recursive deep clone function.

advanced

  • How would you handle circular references in a deep clone function?

Flash Cards

Question

Why does typeof null complicate it?

Click to reveal answer
Answer

Because `typeof null === 'object'`. If your base case is `if (typeof obj === 'object')`, your code will crash when trying to loop over the keys of `null`. You must add an explicit check: `if (obj === null) return null;`.

Question

How to handle circular references?

Click to reveal answer
Answer

You must maintain a cache (usually a `WeakMap`) of objects you have already cloned. Before cloning an object, check the WeakMap. If it exists, return the cached clone. If not, clone it and save it to the WeakMap. This prevents infinite recursion.