Rest Parameter vs Spread Operator
Posted on September 10, 2020 in JavaScript by Matt Jennings
Rest Operator
Rest operator: collects all remaining elements into an array.
See the code example below:
function returnArr(...arr) {
return arr;
}
returnArr(1,2,3,4); // [1,2,3,4];
Spread Operator
Spread operator: allows iterables ( like arrays and strings ) to be expanded into single arguments/elements.
See code examples below:
function xyz(x, y, ...z) {
console.log(x, ' ', y); // hey hello
console.log(z); // ["wassup", "goodmorning", "hi", "howdy"]
console.log(z[0]); // wassup
console.log(z.length); // 4
}
xyz("hey", "hello", "wassup", "goodmorning", "hi", "howdy")
// Adding array elements to an existing array
const arr = ["Joy", "Wangari", "Warugu"];
const newArr = ["joykare", ...arr];
// Copying arrays const arr = [1, 2, 3]; const arr2 = [...arr];