Rest and Spread operators in JS

By placing … before the arrayname as you are passing the array as a argument when calling a function, you can split an array up so the function will see each array value as different arguments.


function sum(x,y) {
	return x + y;
}

let nums = [1, 2];

console.log(sum(...nums));

By placing … before an parameter in the function declaration, values that get sent when calling the function gets grouped together into an array.
This is very useful when you don’t know how many values(arguments) that will be sent into the function.



function sum(...numbers) {
   return numbers.reduce(function(prev, current) {
      return prev+current;
   });
}
console.log(sum(1,2,3));

Add your comment