Sub topic 9
Collecting Arguments with Rest Parameters
This chapter assumes you can declare and call functions, work with arrays and their methods (map, reduce, join), and read template literals. It also builds on two earlier chapters: extra arguments are ignored when no parameter receives them, and the legacy arguments object holds every argument a call passed.
A rest parameter gives a function a clean way to accept any number of arguments. You write three dots before the last parameter name. JavaScript then gathers every argument that no earlier parameter claimed into a real array under that name.
The Working Model
Arguments are matched to parameters from left to right. Each named parameter takes one argument. When those run out, the rest parameter takes everything left over.
function logEvent(level, ...messages) {
console.log(`level=${level}`, messages);
}
logEvent("info", "started", "port 8080"); // level=info [ 'started', 'port 8080' ]
logEvent("warn", "disk low"); // level=warn [ 'disk low' ]
logEvent("debug"); // level=debug []
logEvent(); // level=undefined []These four calls show the rules you need:
messagesis always an array. It is neverundefined.- When nothing is left over, the rest parameter is an empty array
[]. - Named parameters before the rest behave as usual. A missing one is
undefined.
A Real Array, Unlike arguments
The arguments object is array-like. It has indexes and a length, but it has no array methods. A rest parameter is a true Array, so you can call map, filter, reduce, and the rest directly.
function average(...values) {
if (values.length === 0) return 0;
const total = values.reduce((sum, v) => sum + v, 0);
return total / values.length;
}
console.log(average(2, 4, 9)); // 5
console.log(average()); // 0
console.log(Array.isArray((function (...r) { return r; })())); // trueRest parameters have two more advantages over arguments:
| Feature | `arguments` | Rest parameter |
|---|---|---|
| Type | Array-like object | Real `Array` |
| Contains | Every argument | Only the unclaimed arguments |
| Available in arrow functions | No (an arrow function sees the outer function's `arguments`) | Yes |
| Shows intent in the signature | No, the signature looks like it takes nothing | Yes, `...items` is visible |
Arrow functions have no arguments of their own, so a rest parameter is the only way to write a variadic arrow function:
const joinWords = (separator, ...words) => words.join(separator);
console.log(joinWords("-", "a", "b", "c")); // "a-b-c"
console.log(joinWords(", ")); // ""Syntax Rules and the Errors They Cause
Rest parameters have strict placement rules. Breaking any of them is a SyntaxError, so the whole script fails to load instead of failing at call time.
| Rule | Invalid code | Why |
|---|---|---|
| Rest must be last | `function f(...a, b) {}` | Nothing could ever reach `b` |
| Only one rest parameter | `function f(...a, ...b) {}` | The split between them would be ambiguous |
| No trailing comma after rest | `function f(...a,) {}` | A comma implies another parameter follows |
| No default value on rest | `function f(...a = []) {}` | Rest is already `[]` when empty |
Named parameters before the rest can still have defaults:
function tag(name = "div", ...classes) {
return `<${name} class="${classes.join(" ")}">`;
}
console.log(tag(undefined, "card", "wide")); // <div class="card wide">
console.log(tag("span")); // <span class="">The Most Common Mistake: Passing an Array
A rest parameter collects arguments. It does not unwrap an array you pass in. If you hand it one array, you get an array containing that array.
function total(...nums) {
return nums.reduce((sum, n) => sum + n, 0);
}
const prices = [10, 20, 30];
console.log(total(10, 20, 30)); // 60
console.log(total(prices)); // "010,20,30" (nums is [[10, 20, 30]])The second result is a string because 0 + [10, 20, 30] converts the array to the string "10,20,30" and concatenates. No error is thrown, so this bug can go unnoticed. You fix it at the call site by expanding the array into separate arguments with spread syntax, total(...prices). The next chapter covers spread.
If a function should accept either form, decide this on purpose and normalize the input:
function totalFlexible(...nums) {
const list = nums.length === 1 && Array.isArray(nums[0]) ? nums[0] : nums;
return list.reduce((sum, n) => sum + n, 0);
}
console.log(totalFlexible(1, 2, 3)); // 6
console.log(totalFlexible([1, 2, 3])); // 6Use this pattern sparingly. A signature that accepts two shapes is harder to document and to type-check.
Destructuring the Rest Array
The rest parameter can itself be a destructuring pattern. This is rarely needed, but you may see it in existing code:
function firstTwo(...[a, b]) {
return `${a} and ${b}`;
}
console.log(firstTwo("x", "y", "z")); // "x and y"This works the same as function firstTwo(a, b) except that it also changes function.length, which a later chapter covers. Plain named parameters are usually clearer.
Forwarding Arguments in Wrappers
A common real use of rest parameters is a wrapper that adds behavior and passes every argument through unchanged. The rest parameter collects the arguments, and spread passes them on.
function withTiming(fn) {
return (...args) => {
const start = Date.now();
const result = fn(...args);
console.log(`${fn.name} took ${Date.now() - start}ms`);
return result;
};
}
function multiply(a, b) {
return a * b;
}
const timedMultiply = withTiming(multiply);
console.log(timedMultiply(6, 7)); // logs "multiply took 0ms", then 42The wrapper does not need to know how many parameters multiply has. It works for any function.
Decision Guide
- Use a rest parameter when the arguments form a list of similar items, such as numbers to sum, messages to log, or class names to join.
- Use named parameters when each position means something different.
move(x, y)is clearer thanmove(...coords). - Use an options object, covered in a later chapter, when there are several optional settings with different meanings.
- If callers usually already have an array, consider taking one array parameter instead of a rest parameter, so nobody has to remember to spread.
Exercise
Given function f(first, ...others) { return [first, others]; }, what does each call return: f(), f(1), f(1, 2, 3), and f([1, 2])?
Show answer
f() returns [undefined, []]. f(1) returns [1, []]. f(1, 2, 3) returns [1, [2, 3]]. f([1, 2]) returns [[1, 2], []], because the single array argument is bound to first and nothing is left for others.
Exercise
Write an arrow function maxOf that takes a required label followed by any number of numbers and returns a string like "temps: 31". If no numbers are given, return "temps: none". Then explain why function bad(...items, label) {} cannot be used instead.
Show answer
const maxOf = (label, ...nums) => nums.length === 0 ? ${label}: none : ${label}: ${Math.max(...nums)}; For example, maxOf("temps", 22, 31, 18) returns "temps: 31" and maxOf("temps") returns "temps: none". The version bad(...items, label) is a SyntaxError because a rest parameter must be the last parameter. It would take every argument and leave nothing for label.
Exercise
A teammate calls logAll(lines), where function logAll(...lines) { lines.forEach((l) => console.log(l)); } and lines is ["a", "b"]. The output is one line, "[ 'a', 'b' ]", not two lines. Explain the cause and give two possible fixes.
Show answer
The rest parameter wrapped the single array argument, so inside the function lines is [["a", "b"]] and forEach runs once on the inner array. Fix 1: spread at the call site with logAll(...lines). Fix 2: change the signature to take one array parameter, function logAll(lines) { ... }, if callers usually have an array already.