The … operator has been there for a long time since ES6 was introduced in javascript and it is being used for the representation of both the spread and rest operator in javascript. It is a very useful operator that helps javascript developers to manipulate arrays and objects very easily. But the problem with the … operator is most people get confused between the two while learning javascript as … representation is used for both spread and rest operators in javascript. To overcome this challenge we will be discussing with you some of the scenarios and use cases of both spread and rest operator in javascript.
Spread Operator (…)
Let us take the example of a box. The spread operator is generally known for grabbing all the elements of the box without grabbing the box itself and putting all the content wherever we want.
Let us take an example to know more about spread operator in javascript
Example :Â
const box = ["bat","blanket","ball","clothes"];
const someOtherBox = [...box];
function getBoxData(data1,data2,data3,data4){
console.log(data1,data2,data3,data4);
}
getBoxData(...someOtherBox);
Output :

Example :Â
const box = ["bat","blanket","ball","clothes"];
const someOtherBox = ["water-bottles","dryfruits","badminton"];
const box2=[...box,...someOtherBox]
function getBoxData(data1,data2,data3,data4,data5,data6,data7){
console.log(data1,data2,data3,data4,data5,data6,data7);
}
getBoxData(...box2);
Output :

Now we will see how the spread operator works with objects in javascript with an example. In this example, we will also show you how to overwrite the value of key value pair in javascript.
Example :Â
var student = {
name:"Ajay",
age:28,
hobbies:["cricket","singing"]
}
var newStudent = {
...student,
age:29
}
console.log(newStudent);
Output :Â

Rest Operator(…)
Example :Â
function addNumbers(a,b,c,...others){
console.log(others);
return a+b+c;
}
const res = addNumbers(2,5,6,8,9,7,8,9);
console.log(res);
Output :Â

Example :Â
var student = {
name:"Ajay",
age:"28",
hobbies:["Cricket","Singing"]
}
const {...rest} = student;
console.log(rest);
Output :

This is very brief and crisp information about the use of spread and rest operator in javascript. Finally, we can draw a conclusion that spread operator is used to spread the content of an array while the rest operator is used to group or gather elements(arguments to a function) into an array.
Hopefully, by reading this article I am sure that you would have got a decent knowledge about the use case of spread and rest operator in javascript. If you have any other suggestions to improve the quality of this article then you can put them down in the comment section so that we can implement the changes accordingly.