Spread Operator
The JavaScript syntax (...) that expands an iterable (like an array or object) into individual elements, allowing you to copy or merge data structures.
Overview
The spread operator (...) allows an iterable such as an array or object to be expanded in places where zero or more arguments or elements are expected. It's commonly used to copy arrays, combine arrays, pass array elements as function arguments, and copy or merge objects.
Example
javascript// Array spread const arr1 = [1, 2, 3]; const arr2 = [...arr1, 4, 5]; // arr2 = [1, 2, 3, 4, 5] // Function arguments const numbers = [5, 10, 15]; Math.max(...numbers); // 15 // Object spread const user = { name: 'Alice', age: 30 }; const updatedUser = { ...user, age: 31 }; // { name: 'Alice', age: 31 } // Merging objects const combined = { ...obj1, ...obj2 }; // Copying arrays const copy = [...original];
Key Points
- Uses three dots (...) syntax
- Works with arrays, objects, and other iterables
- Creates shallow copies
- Can merge multiple arrays or objects
- Often paired with destructuring
Learn More
- Destructuring - Destructuring assignment
- Array - JavaScript arrays
- Object - JavaScript objects
- MDN: Spread syntax