ES6 really have a lot of nice features for developers to develop codes where Rest and Spread operator are two of them. Although they function opposite of one another, they both uses the same expression of three dotes ‘…’.
Rest Operator
Rest Operator can be explain such as putting the rest of the variables into itself as an array.
Let’s look the the below example. We we try to pass in a list of cars into the printCarList function, the last 3 cars are packed into someCars variable as an array. Notice that before the parameters are passed into the function, there is no need for extra code to pack the list into array object.
This will be useful when there is an unknown number of parameter known before passing.
const printCarList = (firstCar, ...someCars) => {
console.log(firstCar);
for (let i = 0; i < someCars.length; i++) {
console.log(someCars[i]);
}
};
printCarList('car1', 'car2', 'car3', 'car4');
// Output:
// car1
// car2
// car3
// car4
Let’s explore another way of usage here. Here we using parameter destructuring which is another feature from ES6.
Initially, a list of names is received from some previous step. But it is known that the first name is always a teacher’s name while the rest of the names are the student in that class.
const namelist = ['teacherName', 'studentName1', 'studentName2', 'studentName3'];
const [teacherName, ...studentNames] = nameList;
// teacherName = 'teacherName';
// studentNames = ['studentName1', 'studentName2', 'studentName3']
Spread Operator
Spread Operator can be explain in such a way that it will remove its array brackets and lay out all the values one by one.
In the example below, we use the same nameList as the initial value. To show a common usage of this spread operator, we have applied it in the context of adding new elements in front or behind an array. Previous we would need to use ‘splice’ to insert an element at index 0 but Spread Operator is making it easy for us to do the same stuff.
const namelist = ['teacherName', 'studentName1', 'studentName2', 'studentName3'];
const newNameList = [...nameList, 'studentName4'];
// ['teacherName', 'studentName1', 'studentName2', 'studentName3', 'studentName4']
const newNameList1 = ['newTeacherName', ...nameList, 'studentName4'];
// ['newTeacherName', 'teacherName', 'studentName1', 'studentName2', 'studentName3', 'studentName4']
Conclusion
Rest and Spread Operator uses the same symbol to represent but they have different meaning behind. Rest operator will put all the incoming variables into an array whereas Spread operation will layout all the element from an array.
For more in-depth example, can refer here for more info.
No Responses Yet