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

Shallow Clone with Object.assign

Using Object.assign({}, source) for shallow cloning and how it differs from spread syntax.

Shallow Clone with Object.assign

You'll learn how Object.assign({}, source) creates a shallow copy of an object and how it compares to the spread syntax you just learned.

The Alternative Cloning Method

Before the spread operator became popular, Object.assign() was the standard way to clone objects. It copies all enumerable own properties from one or more source objects into a target object:

const original = { name: "Alice", age: 30 };
const clone = Object.assign({}, original);

clone.name = "Bob";

console.log(original.name); // "Alice" (unchanged)
console.log(clone.name);    // "Bob"

The first argument ({}) is the target object that receives the properties. The second argument is the source object being copied.

Object.assign vs Spread Syntax

Both create shallow clones, but there are subtle differences:

const user = { name: "Alice", role: "admin" };

// Using Object.assign
const clone1 = Object.assign({}, user);

// Using spread (what you just learned)
const clone2 = { ...user };

// Both produce the same result for simple cases
console.log(clone1); // { name: "Alice", role: "admin" }
console.log(clone2); // { name: "Alice", role: "admin" }

The key differences:

  • Object.assign() can merge multiple source objects: Object.assign({}, obj1, obj2, obj3)
  • Spread syntax is more concise and modern
  • Both are shallow — nested objects are still referenced, not copied

When to Use Each

Use spread for simple, single-object cloning (cleaner syntax). Use Object.assign() when you need to merge multiple objects or work in environments where spread isn't supported.

Key Takeaway: Object.assign({}, source) creates a shallow clone by copying properties to a new target object, offering more flexibility than spread but with slightly more verbose syntax.