Topic 50 of 87
Spread & Rest
Overview
The three dots (...) syntax was introduced in ES6 and is used extensively in modern React.
Depending on where it is used, it acts as either the Spread Operator (which unpacks elements OUT of an array) or the Rest Parameter (which packs standalone elements INTO an array).
Syntax
1. The Spread Operator
javascript
// Used to expand/unpack an array
const group1 = ["Alice", "Bob"];
const group2 = ["Charlie"];
// Combine arrays easily!
const allUsers = [...group1, ...group2, "David"];
console.log(allUsers); // ["Alice", "Bob", "Charlie", "David"]
// Shallow copy an array safely
const clone = [...group1];2. The Rest Parameter
javascript
// Used in function definitions to condense arguments into an array
function sum(...numbers) {
// 'numbers' is automatically a real array!
return numbers.reduce((acc, n) => acc + n, 0);
}
console.log(sum(1, 2, 3, 4)); // 10Common Pitfalls
- Using the Rest Parameter anywhere except at the very end of a function's argument list.
function process(...args, lastItem)is a SyntaxError. Rest must collect the 'rest' of the remaining arguments at the end.
Interview Questions
Q:
What is the difference between Spread and Rest?
A:
They look identical (...), but do the exact opposite. Spread expands an iterable into individual elements (used in array literals or function calls). Rest condenses multiple individual elements into a single array (used in function definitions).
Real-World Example
Adding a new item to a React state array without mutating the original state.
example
javascript
setTodos(prevTodos => [...prevTodos, newTask]);Check Your Knowledge
Test your understanding of Spread & Rest with these quick questions.