Table of contents
Introduction
Rest and Spread were introduced in ES6 and both have the same Symbol of ... 3 dots.
Even though both have the same symbol, both have different meanings. Let's Simplify these operators.
Spread
Spread (...) allows the iterables such as an array, string, etc. to be unpacked into individual elements separated by a comma.
Use Cases:
- Creating a new Array and adding new values.
const arr1 = [3,4,5];
const arr2 = [...arr1,6,7];
console.log(arr2);
//Output
//arr2 = [3,4,5,6,7]
In this code snippet, the spread operator spreads or unpacks the individual elements of arr1 into arr2 separated by the commas.
It is useful to create a copy of an array.
- Function Arguments
const printSum = (num1,num2,num3) => num1 + num2 + num3;
const num = [2,3,4];
printSum(...num)
//num will look like this:(2,3,4)
It is one of the best use cases of the spread operator. When we get data in form of the array, we can use the spread to pass as an argument.
In the above code, we have a num array and pass this array to function.
When calling we can use spread to unpack the values of the array.
Rest
Rest(...) allows us to create an array from the remaining elements or all elements .
Use Cases:
Destructuring
const arr = [1,2,3,4]; const [firstNum , secondNum , ...rest] = arr; console.log(firstNum,seccondNum,rest); //Output //1 2 [3, 4]
In this code snippet, there is an array, in the second step the destructuring is done and the first and second values are stored in the firstNum and secondNum.
The remaining values of the array are stored in the rest variable using the rest.
Using Spread in the function parameters.
const sumNumbers = (...num) => { console.log(num); return num.reduce((values,acc) => values + acc ,0); } console.log(sumNumbers(1,2,3,4)); //Output: [1,2,3,4] 10
In the above code snippet, the rest operator in the function parameters takes all the arguments and creates an array out of it.
It is very useful as it creates an array and there are various array methods available to use.
Conclusion
Rest should always be the last parameter or variable.
Spread unpacks the array and rest packs it into a new array.