Explanation:
- spread operator is used to:
- spread elements from an iterable into various contexts (arrays, objects, or function calls)
- rest operator is used:
- gather multiple function arguments into an array
- collect remaining elements when destructuring arrays
- “spread” and “rest” are often used interchangeably
- the context determines functionality
examples as follows:
Spread Operator (...
)
used to spread the elements of an iterable (for example an array, string, object) into a new array, object, or function call.
short terms: unpacks the elements of the iterable.
Some Examples as follows:
- Spreading Arrays:
const numbers = [4, 6, 7];
const newArray = [...numbers, 4, 5]; // Creates a new array [4, 6, 7, 4, 5]
- Spreading Objects:
const person = { name: "Amparo", age: 200 };
const newPerson = { ...person, city: "" };
// Creates a new object { name: "Amparo", age: 200 , city: "hhjd-23" }
- Spreading Function Arguments:
function add(x, y) {
return x + y;
}
const numbers = [5, 6];
const sum = add(...numbers);
// Equivalent to add(5, 6)
Rest Operator (...
):
The rest operator is used to gather a variable number of arguments into an array. It collects the remaining arguments into an array, which can then be manipulated as needed.
- Gathering Function Arguments:
function sum(...numbers) {
return numbers.reduce((total, item) => total + item, 0);
}
// returns the sum of all arguments: 19
const result = sum(5, 3, 5, 6);
- Rest Parameter in Destructuring:
const [first, ...rest] = [1, 2, 3, 4];
console.log(first); // 1 (the first one)
console.log(rest); // [2, 3, 4] (the rest)
- Rest in Function Parameters:
function printArgs(first, ...rest) {
console.log(first);
console.log(rest);
}
printArgs(6, 2, 8, 3);
// 6 (the first one)
// [2, 8, 3] (the rest)
that’s all, enjoy!