Course contentsShow
← JavaScript
Lesson 690 of 2,72316. Object Methods and PatternsFree lesson

Shallow Clone with Object Spread

Using the spread operator {...obj} to create a shallow copy and understanding what 'shallow' means.

Shallow Clone with Object Spread

You'll learn how to quickly copy an object using the spread operator and understand why it's called "shallow."

The Spread Operator for Cloning

The spread operator {...obj} creates a new object by copying all enumerable own properties from the original. It's like making a photocopy — you get a new piece of paper, but the content is the same:

const original = { name: 'Alice', age: 30 };
const clone = { ...original };

clone.age = 31;

console.log(original.age); // 30 (unchanged!)
console.log(clone.age);    // 31

The two objects are now independent at the top level. Changing clone doesn't affect original.

What Does "Shallow" Mean?

Here's the catch: spread only copies one level deep. If your object contains nested objects, those nested objects aren't cloned — both the original and clone share references to them:

const person = {
  name: 'Bob',
  address: { city: 'Boston' }
};

const copy = { ...person };

copy.address.city = 'Seattle';

console.log(person.address.city); // 'Seattle' — changed!

Think of it like copying a document that contains a hyperlink. You get a new document, but both documents point to the same website. The nested address object is shared between both.

When to Use Shallow Cloning

Shallow cloning is perfect for simple, flat objects or when you only need to modify top-level properties. It's fast and clean. For deeply nested structures, you'll need deep cloning techniques (like the JSON method you just learned).

Key Takeaway: The spread operator {...obj} creates a shallow clone — copying top-level properties but sharing references to nested objects.