What is Rest operator
The rest parameter will represent an indefinite number of (args)arguments as an array.with the use of rest parameters a function can be called any number of arguments.
The rest parameter is prefix with three dots (...). It is similar to spread operator. Even thought it is complete different from spread operator.It is placed at the last argument because it is used to collect all the remaining elements In an array.
Example function show(...args)
{
let sum = 0;
for (let i of args) {
sum += i;
}
console.log("Sum = "+sum);
}
show(10, 20, 30);
All the arguments we passed in the function will map to the parameter list.
In the above example the rest parameter(…) should always be at last in the list. If it is placed anywhere else ,it will cause an error.
function show(a,...rest, b) { // error };
Spread Operator
The spread operator “spreads” the values in an iterable (arrays, strings) to be expanded into single arguments/elements.
Spread with Arrays
let’s say you have two arrays and want to combine them:
// Create an Array
const tools = ['hammer', 'screwdriver'];
const otherTools = ['wrench', 'saw'];
we use concat() to concatenate the two arrays:
// Unpack the tools Array into the allTools Array
const allTools = [...tools, ...otherTools];
console.log(allTools);
Output ["hammer", "screwdriver", "wrench", "saw"]
We can use push to change the existing array and add a new user
// A new user to be added
const newUser = { id: 3, name: 'Ron' };
users.push(newUser);
Spread allows us to create a new array from an existing one and add new array to the end:
const updatedUsers = [...users, newUser];
console.log(users);
console.log(updatedUsers);
the new array , updatedUsers, has the new user, the original user remains unchanged.
Output [{id: 1, name: "Ben"}
{id: 2, name: "Leslie"}]
[{id: 1, name: "Ben"}
{id: 2, name: "Leslie"}
{id: 3, name: "Ron"}]
Conclusion The spread Operator (…) is a really powerful feature in javascript. Using this we can solve plenty of real-world problems by using this operator.