JavaScript Interview Question #23

What are rest parameters in JavaScript?

JavaScript Fundamentals, Types, Scope & Functions Junior Beginner

Quick Interview Answer

Rest parameter syntax collects zero or more remaining arguments into a real array. It is written with three dots before the final parameter name.

Detailed Explanation

Rest parameter syntax collects zero or more remaining arguments into a real array. It is written with three dots before the final parameter name.

Unlike the older arguments object, a rest parameter is an Array and therefore supports normal array methods directly. A function can have only one rest parameter, and it must be the last parameter in the parameter list.

Code Example

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

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