JavaScript Spread and Rest Operators
The spread (...) and rest (...) syntax use the same three dots but serve different purposes. Spread expands values, while rest collects multiple values into a single array.
Spread can copy or combine array values without modifying the original arrays.
const fruits = ["apple", "banana"];
const vegetables = ["carrot", "potato"];
const foods = [...fruits, ...vegetables];
console.log(foods);
The spread operator provides a simple way to create a shallow copy of an array.
const numbers = [1, 2, 3];
const copy = [...numbers];
console.log(copy);
Spread can also copy and merge object properties.
const user = { name: "Alex" };
const details = { age: 25 };
const profile = { ...user, ...details };
console.log(profile);
Rest parameters collect remaining function arguments into an array.
function sum(...numbers) {
return numbers.reduce((total, n) => total + n, 0);
}
console.log(sum(10, 20, 30));
Rest syntax can collect the remaining values when destructuring arrays or objects.
const [first, ...remaining] = [10, 20, 30, 40];
console.log(first);
console.log(remaining);
Spread expands an iterable or object into individual values. Rest collects multiple values into one variable.
const numbers = [1, 2, 3];
const copy = [...numbers]; // Spread
function show(...values) { // Rest
console.log(values);
}
show(1, 2, 3);
Use spread when you need to expand or copy values, and rest when you need to collect multiple values. Both are useful for writing concise and flexible JavaScript code.