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 an array. This is so great because arrays are nice and easy to operate on. Here's an example:
const add = (param1, ...rest) => {
let sum = param1;
rest.forEach(arg => sum += arg);
return sum;
};
console.log(add(2, 3, 4));
// 9
Top comments (0)