Online Compiler logoOnline Compiler

JavaScript Tutorial

JavaScript Rest Parameters

Rest parameters collect extra function arguments into an array.

They make functions flexible when input count varies.

Why We Need It

Many utilities accept an unknown number of inputs. Rest parameters handle those cases cleanly.

They are clearer and safer than the old arguments object.

Syntax

function name(...rest) { ... }

Basic Example

1. Sum values

function sum(...nums) {
  return nums.reduce((acc, n) => acc + n, 0);
}

console.log(sum(1, 2, 3));

Collect all arguments into an array and reduce.

Real World Example

2. Fixed + rest

function log(level, ...messages) {
  console.log(level, messages);
}

log("info", "start", "loading");

Use rest after fixed parameters.

Multiple Use Cases

Collect Extra Arguments

Rest parameters gather remaining arguments into an array.

They are useful when you do not know how many inputs you will receive.

Position Matters

The rest parameter must be the last parameter.

Only one rest parameter is allowed.

Modern Alternative to arguments

Rest parameters are clearer than the old arguments object.

They work in arrow functions too.

More Examples

3. Forward arguments

function wrap(fn, ...args) {
  return fn(...args);
}

console.log(wrap(Math.max, 3, 9, 2));

Combine rest and spread to forward arguments.

4. Arrow with rest

const join = (...parts) => parts.join("-");

console.log(join("a", "b", "c"));

Rest parameters work in arrow functions.

Comparison

Without

function sum() {
  return Array.from(arguments).reduce((a, b) => a + b, 0);
}

With

function sum(...nums) {
  return nums.reduce((a, b) => a + b, 0);
}

Common Mistakes and Fixes

Putting rest first

Rest must be the last parameter.

Using arguments in arrows

Arrow functions do not have arguments; use rest.

Assuming rest is required

Rest can be an empty array if no extra args are passed.

Interview Questions

Why must rest be last?

It collects all remaining arguments, so it must be at the end.

Can arrows use rest?

Yes, rest works with arrow functions.

Rest vs spread?

Rest collects into an array; spread expands an array.

Practice Problem

Practice: Write a function that multiplies all numbers passed in.

// TODO: function multiply(...nums)

One Possible Solution

function multiply(...nums) {
  return nums.reduce((acc, n) => acc * n, 1);
}

console.log(multiply(2, 3, 4));

Frequently Asked Questions

What does ...args mean?

It collects remaining arguments into an array.

Can I have multiple rest parameters?

No, only one is allowed and it must be last.

How is rest different from spread?

Rest collects arguments, spread expands them.

Try It Yourself

Try passing different counts of numbers.