The Spread Operator & The Rest Parameter

The Spread Operator & The Rest Parameter

The spread operator and the rest parameter were introduced in the ES6 version of JavaScript.

The rest operator serves as an easier way to perform what the 'arguments' object does while the spread syntax replaces the long way of using loops to copy an array into another besides the array methods— Array.from().

The Spread Parameter (...)

The spread parameter can be used:

  1. To turn an array into a list of arguments, to spread out the values as the name implies into each variable.
let fruits = [ 'Apple', 'Orange', 'Mango', 'Strawberry' ];

function sellFruits() {
   console.log( `I sell ${fruits}`)
}
sellFruits(...fruits); // I sell Apple, Orange, Mango, Strawberry

2.To merge arrays. Takes in multiple arrays and joins them into one array.

let fruits = [ 'Apple',  'Mango',  'Orange' ];
let vegetables = [ 'Spinach',  'Tomatoes',  'Eggplant' ];
let fruitsVegetable = [...fruits, ...vegetables];

console.log( fruitsVegetable ); // Apple, Mango, Orange, Spinach, Tomatoes, Eggplant

Apart from arrays, the spread syntax also works on strings and objects.

The Rest Parameter (...)

The rest parameter does the opposite of the spread parameter. It allows the use of multiple arguments by collating them into an array.

The name of the array of the arguments is used as the function parameter with three dots preceding it. And it has to be the last inputted parameter or else it will throw an error.

function thisWillThrowAnError( a, b, ...array, c ){
   console.log('nothing')
}
// Uncaught SyntaxError: Rest parameter must be the last formal parameter

The most common use case of the rest parameter is in the sum of multiple numbers.

function sumAllNumbers(...numbers){
    sum = 0;
    for( let number of numbers){
        sum += number;
     }
    return sum;
}

sumAllNumbers( 1, 2, 3, 4, 5, 6); // 21