This page looks best with JavaScript enabled

Rest Parameter in Javascript

 ·   ·  ☕ 1 min read

Rest parameter enables you to signify an ‘infinite’ parameter to a function.

... serves two purposes in Javascript -

  1. Spread operator - know what spread operators can do
  2. Rest parameter for a function

Rest parameter just tells Javscript that there can be zero or infinite parameters for the function. The elements are available as an array within the function.

1
2
3
4
5
const getSum = (...nums) => {
  console.log(nums); // [ 2, 3, 6 ]
};

getSum(2, 3, 6);

Or, you could do partial parameters..

1
2
3
4
5
6
const getSum = (x, ...nums) => {
  console.log(x); // 2
  console.log(nums); // [3, 6]
};

getSum(2, 3, 6);

You can see similarities between ‘rest’ and ‘spread’, don’t you? While ‘spread’ expands elements of an object, ‘rest’ collects elements in parameter of a function as an array.

My current favourite pattern for passing arguments to functions is to get them all in one beautiful object. The receiving function just refers to whatever variables it is interested in and leaves the rest alone.

Stay in touch!
Share on

Prashanth Krishnamurthy
WRITTEN BY
Prashanth Krishnamurthy
Technologist | Creator of Things