<vetted />
JavaScript
Mid-Level
Question 3 of 10

How do you copy objects and arrays without changing the original?

Quick Answer

Spread operator and Object.assign create shallow copies. For deep copies, use structuredClone or libraries like lodash for nested objects.

Detailed Answer6 paragraphs

Copying in JavaScript requires understanding the difference between shallow and deep copies.

Shallow copies duplicate the top level, but nested objects still reference the originals. The spread operator is the most common approach: const copy = { ...original } or const arrCopy = [...original]. Object.assign({}, original) works similarly. Changes to top-level properties don't affect the original, but modifying nested objects changes both.

Deep copies duplicate everything recursively. structuredClone(obj) is the modern built-in solution—it handles nested objects, arrays, dates, and most built-in types. It doesn't copy functions, DOM nodes, or some special objects.

JSON.parse(JSON.stringify(obj)) was the old workaround. It works for plain data but loses functions, undefined values, dates (become strings), and fails on circular references.

Libraries like lodash provide _.cloneDeep() which handles edge cases and is well-tested. Use it when you need maximum compatibility.

Often you don't need deep copying. Consider whether you actually need a full copy or just a shallow copy of the level you're modifying. For state updates in React, typically you only spread the nesting level you're changing, not the entire deep structure.

Key Takeaway

Spread operator and Object.assign create shallow copies. For deep copies, use structuredClone or libraries like lodash for nested objects.

Ace your interview

Ready to Land Your Dream Job?

Join our network of elite AI-native engineers.