In today’s tutorial we will explain how the rest parameter in Javascript works. Suppose we have a sum function that adds two numbers.

const sum = (num1, num2) => num1 + num2;

We will modify the function sum using the rest parameter in such a way that the function sum is able to take any number of arguments and return their sum.

const sum = (...args) => args.reduce((a, b) => a + b, 0);

console.log(sum(1, 2, 3)) // 6

 

You can use destructuring and the rest operator together to extract the information into variables as you’d like them:

const numbers = [1, 2, 3];
const [ firstNumber, ...restOfTheNumbers ] = numbers;
console.log(firstNumber, restOfTheNumbers);
// 1 [ 2, 3 ]