Spread & Rest Operators in JavaScript
The ...
(three dots) operator is used in two main contexts:
spread (expanding) and rest (gathering). Despite using the same syntax, they serve opposite purposes based on where they are used.
📤 Spread Operator
Used to expand elements from arrays or objects into individual elements.
👉 Arrays:
const arr1 = [1, 2, 3];
const arr2 = [...arr1, 4, 5];
console.log(arr2); // [1, 2, 3, 4, 5]
👉 Objects:
const obj1 = { a: 1, b: 2 };
const obj2 = { ...obj1, c: 3 };
console.log(obj2); // { a: 1, b: 2, c: 3 }
📥 Rest Operator
Used to collect the remaining values into an array or object.
👉 Arrays:
const [first, ...rest] = [10, 20, 30, 40];
console.log(first); // 10
console.log(rest); // [20, 30, 40]
👉 Functions:
function sum(...numbers) {
return numbers.reduce((acc, curr) => acc + curr, 0);
}
console.log(sum(1, 2, 3)); // 6
📌 Differences Summary
Operator | Use Case | Example Context |
---|---|---|
Spread | Expands items | Arrays, objects, function arguments |
Rest | Gathers items | Destructuring, function parameters |
💡 Tip: Use
...rest
to write flexible, dynamic functions and ...spread
to clone or combine data cleanly.