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

Shallow Copying Objects with Spread

Understand how spread creates a new object with copied properties at the first level only.

Shallow Copying Objects with Spread

You'll learn how object spread creates a new object but only copies properties one level deep.

What "Shallow Copy" Means

When you use spread to copy an object, it creates a new object and copies all the properties from the original. However, it only copies at the first level. If any property contains a nested object or array, spread copies the reference to that nested structure, not the structure itself.

Think of it like photocopying a folder of documents. You get a new folder (new object), and copies of the page titles (copied properties), but if one "page" is actually a sticky note pointing to another folder elsewhere, your photocopy just copies that sticky note—it still points to the same other folder.

How It Works

const original = {
  name: "Alice",
  age: 30,
  address: { city: "Boston" }
};

const copy = { ...original };

// Top-level properties are independent
copy.name = "Bob";
console.log(original.name); // "Alice" (unchanged)

// Nested objects are shared!
copy.address.city = "Seattle";
console.log(original.address.city); // "Seattle" (changed!)

The name and age properties were copied, so changing them in copy doesn't affect original. But address is an object, so both original.address and copy.address point to the same object in memory.

When This Matters

Shallow copying is fast and works perfectly when your object has only primitive values (strings, numbers, booleans). But with nested objects, modifications "leak through" to the original.

Key Takeaway: Spread creates a new object and copies properties at the first level only; nested objects and arrays remain shared references between the original and the copy.