Rest parameters of JavaScript

Have you ever dreamed of creating your own JavaScript function that can accept any number arguments? Today we will learn how to do that with modern JavaScript syntax. And as you might already have guessed: the name of that syntax is rest parameter.

Table of contents

Rest parameter

If we put 3 dots(...) before the last parameter of a function, that last parameter is called rest parameter.

If we do so, we can access any number of arguments given to that function from the position of the rest paramter to the right, wrapped in an array. For example:

function foo(a, b, ...c) {
  console.log('a:', a);
  console.log('b:', b);
  console.log('c:', c);
}

foo(1, 2, 3, 4, 5, 6);

It will print the following:

a: 1
b: 2
c: [3, 4, 5, 6]
📝Note: The array that rest parameter gives us is a standard JavaScript array, which means we can use any available array method on it.

That's all there is to know about rest parameter.

Info: The ... in JavaScript can have different meanings based on where it is used. Other JavaScript syntaxes that uses ... are spread syntax and destructuring assignment.

When there was no rest parameter…

From ancient times JavaScript gives all regular functions(non-arrow functions) an local variable named arguments pointing to an array-like object that holds all the arguments we give to it. Developers faces few problems in that approach however. For example:

  • Since it's not an array, array methods don't work on it.
  • We need extra boilerplate code to convert arguments object to an actual array.

In ES6, rest parameter is introduced to overcome these limitations.

Exercises

Do the exercises below to sharpen your understanding:

When no arguments given

What will be the output of the following code:

function foo(...args) {
  console.log(args);
};

foo();
[]

Adder

Write a function named adder that takes a number as the first argument. After the first argument it takes any number of number arguments. What adder does is:

  • It adds the number of 1st argument to all the other numbers it gets and returns all of those resulted numbers wrapped in an array.

There are few ways to solve it. Below is my favorite approach:

const adder = (amount, ...nums) => nums.map(num =>  num + amount);

console.log(adder(1000, 1, 33, 40, 50))
// [1001, 1033, 1040, 1050]

If you found this article helpful, please buy me a coffee