The triple-dot operator (...) is one of the most versatile
tools in modern JavaScript. It serves two different purposes depending on how it's used:
Spread and Rest.
The Spread operator allows an iterable (like an array or string) to be expanded into multiple elements. It is widely used for copying or merging data.
const arr1 = [1, 2, 3];
const arr2 = [...arr1, 4, 5]; // [1, 2, 3, 4, 5]
const combined = [...arr1, ...[6, 7]]; // Merge arrays
const user = { name: "Mim", age: 22 };
const updatedUser = { ...user, city: "Dhaka" }; // Clone and add property
The Rest parameter allows a function to accept an indefinite number of arguments as an array. It "collects" the remaining items.
function sum(...numbers) {
return numbers.reduce((total, n) => total + n, 0);
}
console.log(sum(1, 2, 3, 4)); // Result: 10
const [first, ...others] = [10, 20, 30, 40];
console.log(others); // [20, 30, 40]
While the syntax is identical (...), their mental models are opposite:
...) expands iterables into separate elements...) condenses many elements into a single array