Advertisement
Google Ad Slot: content-top
JS Rest and Spread Operator
The Rest (...) and Spread (...) operators both use three dots (...) but serve different purposes based on their context.
Rest Operator (...)
The Rest Operator is used to collect remaining arguments into an array.
It is primarily used in function parameters.
Example
const [...arr] = [1, 2, 3, 4, 5];
const [first, second, ...rest] = [1, 2, 3, 4, 5];
console.log(arr); // [1, 2, 3, 4, 5]
console.log(first); // 1
console.log(second); // 2
console.log(rest); // [3, 4, 5]
// function
function sum(...numbers) {
return numbers;
}
console.log(sum(1, 2, 3, 4)); // Output: [1,2,3,4]
Spread Operator (...)
The Spread Operator is used to expand iterable elements (like arrays or objects) into individual elements.
Example
const array = [1, 2, 3];
console.log(...array);
// array
const numbers = [1, 2, 3];
const moreNumbers = [...numbers, 4, 5];
console.log(moreNumbers); // [1, 2, 3, 4, 5]
// Object
const obj1 = { a: 1, b: 2 };
const obj2 = { ...obj1, c: 3 };
console.log(obj2); // { a: 1, b: 2, c: 3 }