rest and spread operator

Understanding rest and spread operator

ES6 has some great features that makes working with parameters and arrays easy. JavaScript uses three dots ( … ) for both the rest and spread operators. The main difference between these two operators is that rest operator collects a set of elements and stores them into a single array and spread operator expands an array of elements into a list of individual elements.

Spread operator:

Spread operator expands the values in an iterable like array or strings across zero or more arguments or elements. It is used to split up array of elements and object properties. Using spread operator we can combine two arrays more easily.

const arr1 = ['a','b','c'];
const arr2 = ['d','e','f'];
const combine = [ ...arr1, ...arr2];//spread operator
console.log(combine);
Output:

[ ‘a’, ‘b’, ‘c’, ‘d’, ‘e’, ‘f’ ]

When using spread, we are expanding a single variable into more.

Spread in function call:
function sum(n1,n2)
{
    console.log(n1+n2);
}
let arr=[10,20];
sum(...arr);//spread in function call
Output:

30

As you can see spread operator takes parameters and spreads them across arguments in function call.

What will happen if we have to work with unknown number of parameters?

Answer is using rest operator.

Rest operator:

It’s a collection of remaining elements. Useful for merging functional arguments into an array. We can use when we don’t know how many functional arguments are passed to our method.

const find_greater= (...args) => {

  console.log(args); /* lets see what's in args */

  return console.log(args.filter((x) => x > 25))

}

find_greater(25,36,42,12,17,9,58);
Output:

[25,36,42,12,17,9,58]

[36,42,58]

Another example,
function sum(first, ...others){

  for(let i=0; i<others.length; i++)

    first+=others[i];

  return first;

}

console.log(sum(12,14,22,15,9,7));

let [c,...rest] = [12,14,22,15,9,7];

console.log(...rest);

console.log(c);
Output:

79

14 22 15 9 7

12

Rest parameter have to be at the last because it collects all the remaining parameters into an array.

Rest is a collector. It collects the remaining elements.

Rest vs Spread Operator:
RestSpread
Rest operator allows us to pass an indefinite number of arguments to function by accumulating these several values into an array. Spread operator spreads or expands the values in an array or a string across one or more arguments.
The spread operator in JavaScript expands values in arrays and strings into individual elementsThe rest operator puts the values of user-specified data into a JavaScript array