Skip to main content

Command Palette

Search for a command to run...

Deep Clone in JavaScript — The Right Way (and the Wrong Way)

Updated
3 min read
A

I am developer from India.

When working with objects in JavaScript, one of the most common pitfalls developers run into is accidental mutation. You think you copied an object—but you actually copied a reference.

That’s where deep cloning comes in.


🧠 What is a Deep Clone?

A deep clone creates a completely independent copy of a value.

  • No shared references

  • No side effects

  • Changes in the clone do not affect the original

Example

const obj1 = { user: { role: 'admin' } };
const cloned = deepClone(obj1);

cloned.user.role = 'guest';

console.log(obj1.user.role); // 'admin'
console.log(cloned.user.role); // 'guest'

Most developers start with this:

function deepClone(value) {
  return JSON.parse(JSON.stringify(value));
}

✅ Why it works

  • Handles objects and arrays

  • Very concise

  • No manual recursion


⚠️ Why This Is NOT a Good Interview Answer

Even though it works for simple cases, it has serious limitations:

  • ❌ Removes undefined, function, Symbol

  • ❌ Converts NaN, Infinitynull

  • ❌ Breaks on circular references

  • ❌ Loses prototype chain

  • ❌ Doesn’t support special objects (Date, Map, Set)

👉 In interviews, using this without explanation is a red flag.


✅ The Correct Approach — Recursive Deep Clone

A proper deep clone involves traversing the structure recursively.

function deepClone(value) {
  // Base case: primitives
  if (value === null || typeof value !== "object") {
    return value;
  }

  // Array
  if (Array.isArray(value)) {
    return value.map(item => deepClone(item));
  }

  // Object
  const result = {};
  for (const key in value) {
    result[key] = deepClone(value[key]);
  }

  return result;
}

🧩 How It Works

  • Base case → return primitive values directly

  • Array → clone each element

  • Object → recursively copy each key

This ensures:

  • No shared references

  • Fully independent structure


🚀 Senior-Level Improvement (Prototype Safe)

Want to stand out? Preserve the prototype:

function deepClone(value) {
  if (value === null || typeof value !== "object") {
    return value;
  }

  if (Array.isArray(value)) {
    return value.map(deepClone);
  }

  const result = Object.create(Object.getPrototypeOf(value));

  for (const key of Object.keys(value)) {
    result[key] = deepClone(value[key]);
  }

  return result;
}

✅ Why this matters

  • Keeps object behavior intact

  • Shows deeper JavaScript understanding


🧠 Interview Insight

If you initially mention the JSON approach, always follow it with:

“This works for JSON-safe data, but it fails for functions, undefined, and special objects. A recursive solution is more robust.”

That single line can significantly improve your evaluation.


🏁 Conclusion

Approach When to Use
JSON stringify/parse Quick scripts, safe data
Recursive clone Interviews, real-world usage
Prototype-aware clone Advanced / senior-level understanding

📌 Real Interview Context

This exact deep clone problem has been asked in interviews at:

  • Amazon

  • ByteDance

  • TikTok


If you're preparing for frontend or full-stack roles, this is one of those deceptively simple questions that can quickly reveal how deep your JavaScript fundamentals go.