Adding and Overriding Properties
You'll learn how to combine spread syntax with new property definitions to add or override object properties in a single, clean expression.
The Core Idea
When you spread an object, you can also define new properties or override existing ones in the same object literal. The order matters: properties defined after the spread will override properties from the spread, while properties defined before the spread will be overridden by it.
Think of it like laying down cards: the last card placed on top wins.
Override After Spread
const user = { name: "Alice", age: 25, role: "user" };
const admin = {
...user,
role: "admin", // Overrides user.role
permissions: ["read", "write"] // Adds new property
};
console.log(admin);
// { name: "Alice", age: 25, role: "admin", permissions: ["read", "write"] }
Here, role is overridden because it's defined after spreading user. The permissions property is brand new.
Override Before Spread
const defaults = { theme: "light", notifications: true };
const userSettings = { theme: "dark" };
const finalSettings = {
theme: "light", // This gets overridden
...userSettings // theme: "dark" wins
};
console.log(finalSettings);
// { theme: "dark" }
When you spread after defining a property, the spread's version wins.
Practical Pattern: Updating Objects Immutably
const product = { id: 1, name: "Laptop", price: 999 };
const updatedProduct = {
...product,
price: 899,
onSale: true
};
// product unchanged, updatedProduct has new price and onSale flag
This pattern lets you create modified copies without mutating the original object.
Key Takeaway: Spread an object and add or override properties in the same literal—properties defined after the spread override matching properties from the spread, creating clean, immutable updates.