Skip to content

Variadic Functions Using Rest Parameter

JavaScript/

The rest parameter lets you pass a variable amount of arguments to a function that get nicely packed into a single array. Functions that accept a variable number of arguments are called variadic functions.

The rest parameter, similarly to the spread syntax, must be specified with a prefix of .... It must be the last parameter of the function.

function example(...restParam) {}
function anotherExample(a, ...restParam) {}

// Syntax error
function brokenExample(...restParam, a, b) {}

To use the rest parameter, simply pass as many arguments to the function as you wish.

function example(...restParam) {
  console.log(restParam);
}

// [ 'hi' ]
example('hi');

// [ 'hello', 'world', '.' ]
example('hello', 'world', '.');

// [ 'as', 'many', 'as', 'you', 'want' ]
example('as', 'many', 'as', 'you', 'want');

If the function has other parameters, provide those arguments first.

function example(a, b, ...restParam) {
  console.log(a, b, restParam);
}

// 10 { name: 'Bob' } [ 'all', 'the', 'others', 21 ]
example(10, { name: 'Bob' }, 'all', 'the', 'others', 21);

More Examples

The rest parameter turns the arguments into a regular JavaScript array. Therefore, you can use various useful array methods to process them with ease.

function sum(...numbers) {
  return numbers.reduce((accumulator, current) => accumulator + current);
}

sum(1, 2, 3); // 6
sum(4, 5, 6, 10); // 25
sum(10, 10, 10, 10, 10, 10); // 60

function concatenate(...words) {
  let concatenatedText = '';

  words.forEach(word => concatenatedText += word);

  return concatenatedText;
}

// JavaScript!
concatenate('Java', 'Script', '!');

Perhaps you have come across a function that prints a formatted string. You provide a string in the first argument, that can contain specific symbols. Then you provide the values that get inserted into the string where the specific symbols are located.

function printf(format, ...words) {
  let formattedText = format;

  words.map(word => {
    formattedText = formattedText.replace('%s', word);
  });

  console.log(formattedText);
}

// Today is Monday and the weather is nice
printf('Today is %s and the weather is %s', 'Monday', 'nice');

// My name is Jeff and I am a web developer
printf('My name is %s and I am %s', 'Jeff', 'a web developer');

In this example, any occurrence of %s symbol gets replaced with the words specified in the rest parameter.

You can also use the spread syntax to expand a variable amount of elements as arguments to a variadic function.

function sayHello(...names) {
  names.forEach(name => console.log(`Hello ${name}`));
}

const people = ['Bob', 'Susan', 'Anna', 'John'];

// Hello Bob
// Hello Susan
// Hello Anna
// Hello John
sayHello(...people);

References