Last updated on February 28, 2020
Guys, as we have seen in the previous post about tricks with Spread operator like that we will be going to cover on Rest operator in this post.
Introduction
Rest operator lets us allow to pack the elements into an array. Whereas spread operator is the same opposite. Both operators share the same notation ...
This post will be in short as it’s usage is very straight forward.
Usage
const User ={
add (x, y, ...extras) {
return x + y;
}
};
const sum = User.add(1,23,25,45,26);
From the above code, we have User object which has add method in it which accepts n number of arguments (undetermined).
In that point of time, if you really need only certain number of arguments then we can simply packs the remaining arguments into an array instead of omitting with rest operator.
We will be mostly using this operator in passing function arguments, object and array de-structuring.
// Object De-structuring way
const User = {
firstName : 'Srinivasan',
lastName: 'KK',
getFullName() {
return `${this.firstName} ${this.lastName}`;
}
};
const { firstName, ...remaining } = User;
// remaining would print below result
{lastName: "KK", getFullName: ƒ}
// Array de-structuring
const languages = ['Javascript', 'TypeScript', 'C#', 'Java'];
const [favorite, ...second] = languages;
// second would print
['TypeScript', 'C#', 'Java']
Note
Rest operator would always come last while defining parameters for the function.