JavaScript Rest Parameter Interview Questions and Answers

Review how rest syntax gathers remaining arguments or properties into a single collection.

Frequently Asked Questions

Important questions are highlighted in the sections below; select one to jump to its answer.

Theoretical JavaScript Interview Questions

A rest parameter uses three dots in a function's parameter list to collect the remaining arguments into an array. It must be the final parameter. This differs from spread syntax, which expands an iterable value.

function sum(first, ...remaining) {
  return first + remaining.reduce((total, value) => total + value, 0);
}

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

A rest parameter collects the remaining arguments into a real array. It must be the final parameter in its function parameter list.

It is an empty array, so it can be safely iterated or inspected without a separate missing-arguments check.

Rest parameters are an explicitly named real array containing only remaining arguments; arguments is an array-like object available in many non-arrow functions.

It must be the last formal parameter because it captures all remaining arguments; parameters after it are not allowed.

In a destructuring pattern, ...rest collects the remaining elements into a new array. This is related syntax but distinct from a function rest parameter.

It gathers the remaining enumerable own properties not already selected into a new object.

Rest gathers multiple values into an array or object in a binding pattern; spread expands an iterable or object properties into another expression.

The parameter only collects arguments and performs no type checking. Validate expected types and constraints before using the values.

No. A rest parameter cannot have an initializer; use a default on preceding parameters or handle an empty rest array inside the function.

Declare a rest parameter such as (...items) to collect their arguments. Arrow functions do not have their own arguments object.

Collect the arguments into an array and spread that array into the target call, preserving the intended argument order.

It allocates an array and can encourage large argument lists that are hard to validate or maintain. For streaming or unbounded data, pass an iterable or collection instead.

Repeatedly copying or expanding arguments can add allocation and call overhead. Prefer an iterative approach or pass a stable collection when input can grow substantially.

JavaScript Practical and Coding Interview Questions

Problem: Implement sumAll(...numbers) to return the total, including zero when called without arguments. Log a call with 2, 3, and 5.

javascript

function sumAll(...numbers) {
  return numbers.reduce((total, number) => total + number, 0);
}

console.log(sumAll(2, 3, 5));
console.log(sumAll());