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.

JavaScript
Combining two arrays with spread.
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.

JavaScript
Creating a shallow array copy.
const numbers = [1, 2, 3];
const copy = [...numbers];

console.log(copy);

Spread can also copy and merge object properties.

JavaScript
Merging objects with spread.
const user = { name: "Alex" };
const details = { age: 25 };

const profile = { ...user, ...details };

console.log(profile);

Rest parameters collect remaining function arguments into an array.

JavaScript
Collecting multiple function arguments.
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.

JavaScript
Collecting remaining array values.
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.

JavaScript
Simple comparison of spread and rest.
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.