Using rest parameters in JavaScript functions

Discover how to use rest parameters in JavaScript functions.
December 01, 2020JavaScript
1 min read

The rest parameters syntax provides an easy way to pass an indefinite number of arguments to a function as an array. Rest parameters syntax allows a function to be called with any number of arguments, no matter how it was defined. Rest parameters syntax was added in ES2015 or ES6.

Let's define a function that uses rest parameters.

function sum(...values) { 
  let sum = 0; 
  for (let value of values) { 
    sum += value; 
  } 
  return sum; 
}

console.log(sum(1)); // result is 1
console.log(fun(1, 2)); // result is 3
console.log(fun(1, 2, 3)); // result is 6

Rest parameters at the end

A function can have its first parameters as variables, and gather only the rest using the rest parameters syntax. The rest parameters must be the last entry in a function's parameters because they gather all remaining arguments.

function getFullName(firstName, lastName, ...titles) {
  console.log(titles[0]); // CEO
  console.log(titles[1]); // CIO
  console.log(titles[2]); // COO
  console.log(titles[3]); // undefined
  console.log(titles.length); // 3

  return `${firstName} ${lastName} - ${titles.join(', ')}`;
}

const fullName = getFullName('John', 'Smith', 'CEO', 'CIO', 'COO');
console.log(fullName); // John Smith - CEO, CIO, COO

New
Be React Ready

Learn modern React with TypeScript.

Learn modern React development with TypeScript from my books React Ready and React Router Ready.