DEV Community

Cover image for The Rest Operator
Sam E. Lawrence
Sam E. Lawrence

Posted on

The Rest Operator

I had never heard of the Rest Operator until today, but it's a wonderful inverse twist on the Spread Operator. Let's say you need to add up a series of numbers, but you don't know how many numbers your function needs to take in. The Rest Operator is a great way to take every function argument after the first and combine them (the rest) into a true array. This is so great because arrays are nice and easy to operate on. Here's an example:

function add(param1, ...rest) {
  let sum = param1;
  rest.forEach(arg => sum += arg);
  return sum;
};

console.log(add(2, 3, 4));
// 9
Enter fullscreen mode Exit fullscreen mode

Discussion (0)