Spread Operator
Source: Dev.to
Merging Arrays with the Spread Operator
const array1 = [1, 2, 3];
const array2 = [4, 5, 6];
const mergedArray = [...array1, ...array2];
console.log(mergedArray); // Output: [1, 2, 3, 4, 5, 6]
The spread operator expands the elements of array1 and array2 into a new array, producing a combined list without mutating the original arrays.
Merging Objects with the Spread Operator
Property Overwrite Rules
When objects are merged, properties from later (right‑most) objects overwrite those from earlier ones if they share the same key.
const obj1 = { name: "Alice", age: 30 };
const obj2 = { city: "New York", age: 35 };
const mergedObj = { ...obj1, ...obj2 };
console.log(mergedObj);
// Output: { name: "Alice", age: 35, city: "New York" }
In this example, age from obj2 replaces the age from obj1.
Shallow Copy Behavior
The spread operator creates a shallow copy. Nested objects remain references to the originals.
const obj1 = { name: "Alice", details: { hobby: "reading" } };
const obj2 = { city: "New York", details: { hobby: "hiking" } };
const mergedObj = { ...obj1, ...obj2 };
mergedObj.details.hobby = "painting";
console.log(obj1.details.hobby); // Output: "painting"
Modifying a nested property in mergedObj also affects obj1 because the nested object was not deeply cloned.
Example: Merging User Objects
const user1 = {
name: "John",
age: 40,
admin: true,
};
const user2 = {
name: "Dow",
age: 35,
};
const mergedUser = {
...user1,
...user2,
};
console.log(mergedUser);
// Output: { name: 'Dow', age: 35, admin: true }
Here, the name and age from user2 overwrite those from user1, while the admin flag from user1 is retained.
Note: The spread operator is concise for merging arrays and objects, but its shallow‑copy nature means nested structures are still linked to the originals. For deep merging, consider alternatives such as
Object.assign(with manual recursion) or utility libraries likelodash.merge.