Sub topic 6
Rest Parameters in Functions
This chapter assumes you can declare variables with let and const, write regular and arrow functions, and use common array methods such as map and reduce. It also builds on the previous chapter, where a rest element (...others) collected leftover values inside a destructuring pattern. A rest parameter uses the same idea in a function's parameter list.
The Working Model
A rest parameter is a final parameter written with ... in front of its name. When the function is called, JavaScript fills the ordinary parameters by position first. Every argument left over goes into a new, real array bound to the rest parameter.
function logAll(label, ...items) {
console.log(label, items.length, items);
}
logAll('none'); // none 0 []
logAll('two', 'a', 'b'); // two 2 ['a', 'b']
logAll('many', 1, 2, 3, 4); // many 4 [1, 2, 3, 4]The rules behind this behavior are:
- The rest parameter is always an array. If no arguments are left over, it is an empty array, never
undefined. - It only collects arguments that were not already taken by earlier parameters.
- Each call creates a fresh array, so changing it inside the function does not affect the caller or other calls.
Arguments passed explicitly as undefined still count. They are collected like any other value:
function collect(first, ...rest) {
return rest;
}
console.log(collect(1, undefined, 3)); // [undefined, 3]
console.log(collect()); // [] (first is undefined, rest is empty)Rest Parameters vs the `arguments` Object
Before ES2015, a function that accepted any number of arguments read them from arguments. That is an array-like object available inside regular (non-arrow) functions. It has indexes and a length, but it is not an array, so array methods are missing.
function oldStyle() {
console.log(Array.isArray(arguments)); // false
return Array.prototype.slice.call(arguments).map((n) => n * 2);
}
function newStyle(...nums) {
console.log(Array.isArray(nums)); // true
return nums.map((n) => n * 2);
}
console.log(oldStyle(1, 2, 3)); // [2, 4, 6]
console.log(newStyle(1, 2, 3)); // [2, 4, 6]| Feature | `arguments` | Rest parameter |
|---|---|---|
| Type | Array-like object | Real `Array` |
| Array methods (`map`, `filter`, ...) | Not available directly | Available |
| Contents | All arguments | Only arguments after the named ones |
| Available in arrow functions | No (arrows see the outer function's `arguments`) | Yes |
| Name shown in the signature | No | Yes, so callers can see it |
| Linked to named parameters in sloppy mode | Yes, for simple parameter lists | No |
Arrow Functions Have No `arguments`
Arrow functions do not get their own arguments. If you use arguments inside an arrow, you get the arguments of the nearest enclosing regular function. That is a common source of confusing bugs.
function outer() {
const inner = () => arguments[0];
return inner('ignored');
}
console.log(outer('from outer')); // 'from outer'For a variadic arrow function, a rest parameter is the only clean option. A variadic function is one that accepts a variable number of arguments.
const average = (...nums) =>
nums.length === 0 ? 0 : nums.reduce((total, n) => total + n, 0) / nums.length;
console.log(average()); // 0
console.log(average(2, 4, 9)); // 5Combining Required Parameters with Rest
A good variadic signature names the arguments the function needs and collects the rest. This documents intent better than reaching into arguments[0].
function className(base, ...modifiers) {
return [base, ...modifiers.map((m) => `${base}--${m}`)].join(' ');
}
console.log(className('btn')); // 'btn'
console.log(className('btn', 'primary', 'large')); // 'btn btn--primary btn--large'The ...modifiers.map(...) inside the array literal is spread, not rest. The next chapter covers it. The rule of thumb is that in a parameter list or pattern, ... collects, and in a call or literal, ... expands.
Syntax Rules and Errors
A rest parameter has strict placement rules. Breaking any of them is a SyntaxError at parse time, so the code never runs. The snippet below uses new Function so each error can be caught and printed.
const attempts = [
'...a, b', // rest must be last
'...a, ...b', // only one rest parameter
'...a = []', // rest cannot have a default
'...a,', // no trailing comma after rest
];
for (const params of attempts) {
try {
new Function(params, '');
console.log(params, '-> ok');
} catch (err) {
console.log(params, '->', err.name); // SyntaxError for every case
}
}| Rule | Invalid | Why |
|---|---|---|
| Must be the last parameter | `(...a, b)` | Nothing would be left for `b` |
| Only one per function | `(...a, ...b)` | The split between them would be ambiguous |
| No default value | `(...a = [])` | It is always an array, so a default is never needed |
| No trailing comma | `(...a,)` | A comma implies another parameter follows |
Effect on `function.length`
A function's length property reports how many parameters it expects. The rest parameter is not counted. Counting also stops at the first parameter with a default value.
function a(x, y, ...rest) {}
function b(x, y = 0, ...rest) {}
function c(...rest) {}
console.log(a.length); // 2
console.log(b.length); // 1
console.log(c.length); // 0This matters for code that inspects length, such as some currying helpers and test frameworks that decide whether a callback takes a done argument. If you add a rest parameter to a function passed to such a tool, its detected arity can change.
No Link to Named Parameters
In sloppy (non-strict) mode, a function with only plain parameters has a mapped arguments object. Assigning to arguments[0] changes the first parameter, and the reverse also holds. Adding a rest parameter makes the parameter list non-simple, which turns off that link, just as strict mode does. The rest array is also independent:
function edit(first, ...rest) {
rest[0] = 'changed';
arguments[0] = 'also changed';
return [first, rest, arguments[1]];
}
console.log(edit('a', 'b')); // ['a', ['changed'], 'b']Here first keeps 'a', and arguments[1] still holds the original 'b'. Changing one never changes the others.
Destructuring the Rest Parameter
Because the rest parameter is a binding target, you can write a destructuring pattern in place of its name:
function firstTwo(...[x, y]) {
return `${x}/${y}`;
}
console.log(firstTwo(1, 2, 3)); // '1/2'
console.log(firstTwo.length); // 0This is valid but rarely the best choice. Ordinary parameters (x, y) say the same thing more clearly and report a useful length. Use plain rest names unless you have a specific reason.
Forwarding Arguments
Wrapper functions are a common real-world use. Rest collects whatever the caller passed, and spread passes it on unchanged. The wrapper does not need to know the wrapped function's signature.
function withLogging(fn) {
return (...args) => {
console.log(`calling ${fn.name} with`, args);
return fn(...args);
};
}
function add(a, b) {
return a + b;
}
const loggedAdd = withLogging(add);
console.log(loggedAdd(2, 3)); // logs: calling add with [2, 3], then prints 5Common Mistakes
- Expecting
undefinedwhen nothing is passed. The rest parameter is[], soif (!items)is never true. Checkitems.length === 0. - Using
argumentsinside an arrow function. It silently refers to the enclosing function's arguments, or throws aReferenceErrorif there is no enclosing function, as in an ES module. - Passing an array where separate arguments are expected.
sum([1, 2, 3])givesnums = [[1, 2, 3]]. Callsum(...arr)or change the API to take an array. - Assuming
lengthincludes the rest parameter. It does not.
Exercise
Given function f(a, b = 2, ...c) { return [a, b, c]; }, what do f(1), f(1, undefined, 3, 4), and f.length return?
Show answer
f(1) returns [1, 2, []], because b takes its default and c is an empty array. f(1, undefined, 3, 4) returns [1, 2, [3, 4]], because passing undefined explicitly still triggers the default for b, and the remaining arguments go into c. f.length is 1, because counting stops at the first parameter with a default and the rest parameter is never counted.
Exercise
Rewrite function max() { let m = -Infinity; for (let i = 0; i < arguments.length; i++) { if (arguments[i] > m) m = arguments[i]; } return m; } as an arrow function that requires at least one argument named first and uses a rest parameter for the others.
Show answer
const max = (first, ...others) => others.reduce((m, n) => (n > m ? n : m), first); Calling max(3, 9, 4) returns 9, and max(5) returns 5, because reduce on an empty array with an initial value returns that value.
Exercise
Why is function g(...items = []) {} a SyntaxError, and what does items hold if g is called with no arguments once the default is removed?
Show answer
A rest parameter cannot have a default, because JavaScript always creates an array for it. With the default removed, calling g() gives items an empty array [], so the default would never have been needed.