What is the Spread Operator?
The spread operator (...) "spreads" the elements of an array or object into a new array, object, or function arguments.
💡 Key insight
The spread operator creates a shallow copy — it copies the top-level structure, but nested objects are still shared by reference.
Spread with Arrays
let arr1 = [1, 2, 3];
let arr2 = [4, 5, 6];
// Copy an array
let copy = [...arr1]; // [1, 2, 3]
// Merge arrays
let merged = [...arr1, ...arr2]; // [1, 2, 3, 4, 5, 6]
// Add elements
let newArr = [0, ...arr1, 4]; // [0, 1, 2, 3, 4]
Spread with Objects
let obj1 = { name: "Alice", age: 25 };
let obj2 = { city: "New York", country: "USA" };
// Copy an object
let copy = { ...obj1 };
// Merge objects
let merged = { ...obj1, ...obj2 };
// Override properties (last one wins)
let updated = { ...obj1, age: 26 };
Rest Parameters
The rest operator collects remaining elements into an array.
// In function parameters
function sum(...numbers) {
return numbers.reduce((total, n) => total + n, 0);
}
sum(1, 2, 3, 4); // 10
// In array destructuring
let [first, ...rest] = [1, 2, 3, 4];
console.log(first); // 1
console.log(rest); // [2, 3, 4]
Common Mistakes
- Using spread on non-iterable objects (works for arrays and objects)
- Modifying the original array when you meant to create a copy
- Confusing spread with rest (spread expands, rest collects)
Quick Quiz
1. What does [...arr1, ...arr2] do?
2. What does the rest operator do in function sum(...args)?
3. Which is correct for copying an object?
Summary
- Spread (
...) expands elements:[...arr],{...obj} - Use spread to copy or merge arrays and objects
- Rest (
...) collects remaining elements into an array - Rest parameters in functions:
function(...args) - Spread and rest use the same syntax but different contexts
