Copying Objects with Spread and Object.assign
What You'll Learn
You'll learn how to create shallow copies of objects using the spread operator and Object.assign() to avoid mutating original data.
Why Copy Objects?
In functional programming, we never modify existing objects. Instead, we create new ones with our changes. Think of it like making a photocopy of a document before marking it up—the original stays pristine.
Two Ways to Copy
Using the Spread Operator
The spread operator (...) creates a new object with all properties from the original:
const user = { name: 'Alice', age: 30 };
const userCopy = { ...user };
userCopy.age = 31;
console.log(user.age); // 30 (original unchanged)
console.log(userCopy.age); // 31
Using Object.assign()
Object.assign() copies properties from one or more source objects into a target object:
const user = { name: 'Alice', age: 30 };
const userCopy = Object.assign({}, user);
userCopy.age = 31;
console.log(user.age); // 30 (original unchanged)
Making Updates While Copying
Both techniques let you add or override properties while copying:
const user = { name: 'Alice', age: 30 };
// With spread
const updated = { ...user, age: 31, city: 'Boston' };
// With Object.assign
const updated2 = Object.assign({}, user, { age: 31 });
Important: Shallow Copies Only
Both methods create shallow copies. Nested objects are still referenced, not copied:
const user = { name: 'Alice', address: { city: 'Boston' } };
const copy = { ...user };
copy.address.city = 'NYC';
console.log(user.address.city); // 'NYC' (oops! shared reference)
Key Takeaway: Use spread ({ ...obj }) or Object.assign({}, obj) to create shallow copies of objects, enabling immutable updates where the original object remains unchanged.