Skip to main content

...rest parameters

What are rest parameters

Rest parameters let you collect the remaining arguments of a function into a single array.

Syntax:

javascript
function func(...args) { // args is an array of all passed arguments }

Example: sum of all numbers

javascript
function sum(...numbers) { return numbers.reduce((total, n) => total + n, 0); } console.log(sum(1, 2, 3, 4)); // 10 console.log(sum(5, 10)); // 15

Here:

  • numbers is the array [1, 2, 3, 4] or [5, 10]
  • The number of arguments is not fixed

Rest parameters always come last

javascript
function show(first, second, ...rest) { console.log(first); // first argument console.log(second); // second console.log(rest); // array of all the rest } show("a", "b", "c", "d", "e"); // "a" // "b" // ["c", "d", "e"]

You cannot specify other parameters after a rest parameter:

javascript
function badExample(...args, last) {} // Error

Difference from arguments

Propertyarguments...rest
TypeArray-like objectReal array
Array methods (map, reduce)NoYes
Works in arrow functionsNoYes
Name is set explicitlyNoYes
Modern standardOldES6+

Comparison example:

javascript
function old() { console.log(arguments); // [Arguments] { '0': 1, '1': 2 } } const modern = (...args) => { console.log(args); // [1, 2] }; old(1, 2); modern(1, 2);

Another example - filtering arguments

javascript
function filterNumbers(min, ...numbers) { return numbers.filter(n => n > min); } console.log(filterNumbers(10, 5, 15, 8, 25)); // [15, 25]

The first argument min is used separately, and all the rest (15, 8, 25) go into the numbers array.


Rest parameters with destructuring

javascript
function logUser({ name, age, ...rest }) { console.log(name, age); // "Tim" 25 console.log(rest); // { city: "Kyiv", active: true } } logUser({ name: "Tim", age: 25, city: "Kyiv", active: true });

Here ...rest collects all the other object properties that were not among the explicitly listed ones (name, age).


Combination with the spread operator

... plays two different roles:

  • In function parameters -> rest (collects arguments into an array)
  • In a function call -> spread (expands an array into arguments)
javascript
function sum(...nums) { return nums.reduce((a, b) => a + b, 0); } const values = [1, 2, 3]; console.log(sum(...values)); // 6

Quick summary

FeatureDescription
Syntaxfunction fn(...args) {}
TypeArray
Number of argumentsArbitrary
Array methodsWork
OrderRest parameter is always last
Replacement for argumentsYes

Simple analogy

...rest is like a "collector of arguments": if you pass many values, it neatly gathers all the extras into an array.

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.