Sub topic 7
Default and Rest Parameters
This chapter assumes you know function declarations, function expressions, and arrow syntax from earlier chapters, and that you can use basic array methods such as reduce. Default and rest parameters behave the same in all three function forms.
Default Parameters
A default parameter gives a parameter a fallback value. JavaScript uses that value when the argument is missing or explicitly undefined. A rest parameter, written ...name, collects every remaining argument into a real array.
function greet(name = 'world', ...rest) {
return `Hello, ${name}! (${rest.length} extra)`;
}
console.log(greet()); // Hello, world! (0 extra)
console.log(greet('Ada', 1, 2, 3)); // Hello, Ada! (3 extra)Only `undefined` triggers the default
Other falsy values such as null, 0, and '' are treated as real arguments. A common mistake is expecting null to fall back to the default.
function label(text = 'none') {
return `[${text}]`;
}
console.log(label()); // [none]
console.log(label(undefined)); // [none]
console.log(label(null)); // [null]
console.log(label('')); // []If you want null to fall back too, use text ?? 'none' inside the body.
Defaults are evaluated on every call
The default expression runs each time the function is called without that argument. This means a default of [] gives you a fresh array on every call, and state does not leak between calls.
function addItem(item, list = []) {
list.push(item);
return list;
}
console.log(addItem('a')); // [ 'a' ]
console.log(addItem('b')); // [ 'b' ]Defaults can use earlier parameters
Parameters are initialized from left to right. A default can refer to a parameter declared before it. A parameter declared after it is still in the temporal dead zone, so referring to it throws.
const area = (width, height = width) => width * height;
console.log(area(3)); // 9
console.log(area(3, 4)); // 12
function bad(a = b, b = 1) {
return a + b;
}
try {
bad();
} catch (e) {
console.log(e instanceof ReferenceError); // true
}Rest Parameters
A rest parameter gives you a genuine Array, so map, reduce, and filter work on it directly. It works in arrow functions too, which matters because arrows have no arguments object of their own (the next chapter covers this).
const sum = (...numbers) => numbers.reduce((total, n) => total + n, 0);
console.log(sum()); // 0
console.log(sum(1, 2, 3)); // 6
function tag(prefix, ...words) {
return words.map(w => `${prefix}${w}`);
}
console.log(tag('#', 'js', 'web')); // [ '#js', '#web' ]The rules are strict:
| Rule | Violation | Result |
|---|---|---|
| Rest must be last | `function f(...a, b) {}` | SyntaxError |
| Only one rest parameter | `function f(...a, ...b) {}` | SyntaxError |
| Rest cannot have a default | `function f(...a = []) {}` | SyntaxError |
| Empty when no extras | `sum()` | `numbers` is `[]` |
Effect on `length`
A function's length property counts only the parameters before the first default or rest parameter. Libraries that check fn.length to decide how to call a function can behave differently after you add a default.
function f(a, b = 2, ...c) {}
const g = (a, b) => {};
console.log(f.length); // 1
console.log(g.length); // 2Exercise
Given function pad(str, width = 5, char = ' ') { return str.padStart(width, char); }, what do pad('7', undefined, '0') and pad('7', null, '0') return, and why?
Show answer
pad('7', undefined, '0') returns '00007' because undefined triggers the default width of 5. pad('7', null, '0') returns '7' because null is a real argument. padStart converts null to 0, and a target width of 0 adds no padding.
Exercise
Rewrite function max() { return Math.max.apply(null, arguments); } as an arrow function that also returns -Infinity when it gets no arguments.
Show answer
const max = (...nums) => Math.max(...nums); The rest parameter collects the arguments into an array and spread passes them back to Math.max. With no arguments, Math.max() already returns -Infinity.