The spread operator (...) in JavaScript is used to expand elements of an iterable (like an array or object) into individual elements.
function sum(a, b, c) { return a + b + c; } const numbers = [1, 2, 3]; console.log(sum(...numbers)); // β Equivalent to sum(1, 2, 3) β Output: 6
β The spread operator unpacks the array elements into separate arguments.
const arr1 = [1, 2, 3]; const arr2 = [4, 5, 6]; const combined = [...arr1, ...arr2]; console.log(combined); // β [1, 2, 3, 4, 5, 6]
β
Alternative to concat() , creating a new merged array.
const original = [1, 2, 3]; const copy = [...original]; console.log(copy); // β [1, 2, 3] console.log(copy === original); // β false (new array, not the same reference)
β Prevents accidental mutation by creating a new array instead of referencing the original.
const obj1 = { a: 1, b: 2 }; const obj2 = { c: 3, d: 4 }; const merged = { ...obj1, ...obj2 }; console.log(merged); // β { a: 1, b: 2, c: 3, d: 4 }
β
Alternative to Object.assign() , creating a new object.
const objA = { a: 1, b: 2 }; const objB = { b: 99, c: 3 }; const newObj = { ...objA, ...objB }; console.log(newObj); // β { a: 1, b: 99, c: 3 }
β
The b property in objA is overwritten by b in objB.
...) Operator| Feature | Spread (...) | Rest (...) |
|---|---|---|
| Purpose | Expands elements | Collects elements |
| Where itβs used | Function calls, arrays, objects | Function parameters |
| Example | sum(...[1,2,3])βsum(1,2,3) | function sum(...args) {} |
// Spread: Expands const numbers = [1, 2, 3]; console.log(Math.max(...numbers)); // β Expands array to arguments // Rest: Collects function sum(...args) { return args.reduce((acc, val) => acc + val, 0); } console.log(sum(1, 2, 3)); // β Gathers all arguments into an array
β Spread "spreads out", Rest "gathers in".
const user = { name: "Alice", age: 25 }; const updatedUser = { ...user, age: 26 }; console.log(updatedUser); // β { name: "Alice", age: 26 }
β Useful for immutable state updates (React, Redux, etc.).
const person = { name: "Bob", age: 30, city: "NYC" }; const { city, ...rest } = person; console.log(rest); // β { name: "Bob", age: 30 }
β
Removes city from person without modifying the original object.
const word = "Hello"; const letters = [...word]; console.log(letters); // β ["H", "e", "l", "l", "o"]
β Useful for string manipulation.
| Feature | Example | Use Case |
|---|---|---|
| Function arguments | sum(...[1,2,3]) | Passing array elements as arguments |
| Array merging | [...arr1, ...arr2] | Combining arrays |
| Array copying | [...original] | Creating a shallow copy |
| Object merging | { ...obj1, ...obj2 } | Merging objects |
| Object modification | { ...user, age: 30 } | Updating properties immutably |
| String to array | [..."Hello"] | Splitting a string into characters |
π‘ Final Thought:
The spread operator (...) is one of JavaScript's most powerful tools for working with arrays, objects, and function arguments in a clean, concise way.
Test your understanding with 3 quick questions