Course contentsShow
← JavaScript
Lesson 979 of 2,72322. Spread and RestFree lesson

Common Object Spread Pitfalls

Identify mistakes like expecting deep clones or spreading null/undefined without guards.

Common Object Spread Pitfalls

You'll learn to identify and avoid the most common mistakes developers make when using object spread syntax.

The Shallow Copy Trap

The biggest pitfall is assuming spread creates a deep clone. It doesn't! Object spread only copies the top level—nested objects and arrays remain references to the original data:

const user = {
  name: "Alice",
  address: { city: "Boston" }
};

const copy = { ...user };
copy.address.city = "New York";

console.log(user.address.city); // "New York" — original changed!

Think of spread like photocopying a document that contains a business card. You get a new document, but the business card inside is still the same physical card in both copies.

The Null/Undefined Crash

Spreading null or undefined causes runtime errors:

const config = null;
const settings = { ...config }; // TypeError: Cannot spread non-iterable

Always guard against this:

const settings = { ...(config || {}) }; // Safe: spreads empty object if null

The Property Loss Pitfall

Remember that spread only captures enumerable own properties. Non-enumerable properties, inherited properties, and prototype methods vanish:

const parent = { inherited: "value" };
const child = Object.create(parent);
child.own = "data";

const copy = { ...child }; // Only { own: "data" }
console.log(copy.inherited); // undefined

The Order Confusion

Properties can accidentally override intended values if you don't pay attention to spread order:

const defaults = { color: "blue", size: "medium" };
const overridden = { ...{ color: "red" }, ...defaults }; // color becomes "blue"!

Key Takeaway: Object spread creates shallow copies only, crashes on null/undefined without guards, ignores non-enumerable and inherited properties, and follows left-to-right override order—understanding these limitations prevents subtle bugs in your code.