Sub topic 7
Default and Rest Parameters
This chapter assumes you can write function declarations, function expressions, and arrow functions, and that you know how let and const behave before they are initialized (the temporal dead zone). Default parameters and rest parameters let a function's signature describe the values it expects, so the body no longer has to repair missing values or dig through extra arguments by hand.
Default Parameters
A default parameter is a parameter with a fallback value written after =. When the caller leaves that argument out, the parameter gets the fallback.
function makeTag(name, className = 'default') {
return `<${name} class="${className}">`;
}
console.log(makeTag('div')); // <div class="default">
console.log(makeTag('div', undefined)); // <div class="default">
console.log(makeTag('div', null)); // <div class="null">
console.log(makeTag('div', '')); // <div class="">Only `undefined` triggers the default
The default is used when the argument is undefined. It makes no difference whether the caller omitted the argument or passed undefined explicitly. Other falsy values, including null, 0, '', and false, are real arguments and replace the default. The older pattern className = className || 'default' behaved differently, because it also replaced 0 and ''. That was a common source of bugs. If you also want null to fall back, write value ?? fallback in the body.
Defaults are evaluated on every call
A default expression is not computed once when the function is defined. It runs on every call that needs it, so each call that uses [] or {} as a default gets a fresh object. Python programmers should note this, because Python evaluates defaults only once.
function append(item, list = []) {
list.push(item);
return list;
}
console.log(append(1)); // [ 1 ]
console.log(append(2)); // [ 2 ] (a new array, not [1, 2])Because the expression runs lazily, it can call functions. Those functions run only when the default is actually needed:
let calls = 0;
function nextId() {
calls += 1;
return calls;
}
function createUser(name, id = nextId()) {
return { name, id };
}
console.log(createUser('Ada')); // { name: 'Ada', id: 1 }
console.log(createUser('Grace', 99)); // { name: 'Grace', id: 99 }
console.log(createUser('Linus')); // { name: 'Linus', id: 2 }
console.log(calls); // 2Defaults can use earlier parameters, but not later ones
Parameters are initialized left to right. A default can refer to any parameter before it. A parameter after it is still in the temporal dead zone at that point, the same as a let variable read before its declaration.
function rect(width, height = width) {
return width * height;
}
console.log(rect(4)); // 16
console.log(rect(4, 2)); // 8
function bad(a = b, b = 1) {
return a + b;
}
try {
bad();
} catch (e) {
console.log(e instanceof ReferenceError); // true
}
console.log(bad(5)); // 6 (a's default never runs, so b is never read early)The last line shows that the error only happens when the default expression actually runs.
Making a parameter required
JavaScript has no syntax for required parameters. A small helper used as a default covers this, because it runs only when the argument is missing:
function required(name) {
throw new TypeError(`Missing argument: ${name}`);
}
function connect(url = required('url'), retries = 3) {
return `${url} x${retries}`;
}
console.log(connect('db://local')); // db://local x3
try {
connect();
} catch (e) {
console.log(e.message); // Missing argument: url
}Options objects: destructuring with defaults
Once a function has more than two or three optional settings, positional defaults get awkward. A caller who only wants to change the fourth setting has to pass undefined three times. Instead, take a single options object, destructure it, and give each property its own default:
function fetchData(url, { method = 'GET', timeout = 5000 } = {}) {
return `${method} ${url} (${timeout}ms)`;
}
console.log(fetchData('/api')); // GET /api (5000ms)
console.log(fetchData('/api', { method: 'POST' })); // POST /api (5000ms)
console.log(fetchData('/api', { timeout: 100 })); // GET /api (100ms)The = {} at the end matters. Without it, fetchData('/api') tries to destructure undefined and throws TypeError: Cannot destructure property 'method' of 'undefined'. The defaults work at two levels: the outer default supplies an object when none was passed, and the inner defaults fill in the properties that object lacks.
Parameters have their own scope
When any parameter has a default, the parameter list gets its own scope, separate from the function body. A closure created inside a default captures that parameter scope, so it cannot see variables declared in the body:
const x = 'outer';
function show(read = () => x) {
const x = 'inner';
return read();
}
console.log(show()); // outerYou will rarely write code like this on purpose. It does explain an otherwise confusing result: a default never refers to a body variable with the same name.
Rest Parameters
A rest parameter, written ...name, collects all remaining arguments into a real array. "Remaining" means every argument after the named parameters that come before it.
function log(level, ...messages) {
console.log(Array.isArray(messages)); // true
return `[${level}] ${messages.join(' ')}`;
}
console.log(log('info', 'server', 'started', 'on', 8080));
// [info] server started on 8080
console.log(log('warn'));
// [warn] (messages is an empty array, never undefined)Because messages is a real Array, map, filter, join, and every other array method work on it directly. If no extra arguments are passed, it is an empty array, so you never need to check whether it exists.
Rest parameters work the same way in arrow functions. That matters because arrow functions have no arguments object of their own, which a later chapter covers.
const max = (...nums) => (nums.length ? Math.max(...nums) : null);
console.log(max(3, 9, 4)); // 9
console.log(max()); // nullThat example uses ... twice with opposite meanings. In the parameter list, ...nums gathers arguments into an array (rest). In the call Math.max(...nums), it unpacks the array back into separate arguments (spread). Which one you get depends on where the ... appears.
Combining Them, and the Rules
Defaults and rest can appear in the same signature, and both work in arrows. An arrow function with a default or rest parameter must put its parameters in parentheses, even when there is only one: (n = 1) => n and (...xs) => xs are valid, but n = 1 => n is not.
const inc = (n, step = 1) => n + step;
function tagAll(tag = 'li', ...items) {
return items.map((item) => `<${tag}>${item}</${tag}>`).join('');
}
console.log(inc(5)); // 6
console.log(tagAll(undefined, 'a', 'b')); // <li>a</li><li>b</li>The second call shows a problem with putting a default before a rest parameter: to reach the rest items, the caller has to fill the defaulted slot with undefined. As a rule, put defaulted parameters after required ones and keep the rest parameter last.
These signatures are syntax errors. They fail when the code is parsed, so none of the code runs:
| Signature | Why it fails |
|---|---|
| `function f(...a, b) {}` | A rest parameter must be last |
| `function f(...a, ...b) {}` | Only one rest parameter is allowed |
| `function f(...a = []) {}` | A rest parameter cannot have a default (it is already `[]`) |
| `function f(...a,) {}` | A trailing comma after a rest parameter is not allowed |
| `function f(a = 1) { 'use strict'; }` | A function with defaults, rest, or destructured parameters cannot contain its own `'use strict'` directive |
The last row trips people up when they add defaults to old code. Put 'use strict' at the top of the file instead, or use modules and classes, which are strict automatically.
Effect on `function.length`
A function's length property reports how many parameters it expects. It counts only the parameters before the first default or rest parameter:
function a(x, y) {}
function b(x, y = 1) {}
function c(x, y = 1, z) {}
function d(x, ...rest) {}
console.log(a.length, b.length, c.length, d.length); // 2 1 1 1Most code never reads length. Some libraries do, such as currying helpers and test frameworks that check whether a callback takes a done argument. Adding a default to a parameter can change how those libraries treat your function.
Common Errors
- Expecting
null,0, or''to trigger a default. Onlyundefineddoes. - Forgetting the
= {}after a destructured options parameter, so a call with no options throws. - Referring to a later parameter in a default and getting a
ReferenceError. - Writing a one-parameter arrow with a default or rest parameter without parentheses.
- Using
argumentsinside an arrow function where...argswas needed.
Exercise
What does each call print, and why? function pad(text, width = 5, char = ' ') { return text.padStart(width, char); } console.log(pad('7', 3, '0')); console.log(pad('7', null, '0')); console.log(pad('7', undefined, '0'));
Show answer
'007', '7', and ' 7' ... no: the third prints '00007'. The first passes width 3, giving '007'. The second passes null, which is not undefined, so the default is skipped. padStart converts null to 0, and a target width of 0 adds no padding, so it prints '7'. The third passes undefined for width, so width becomes 5 and char is '0', giving '00007'.
Exercise
Rewrite function sumAll() { return Array.prototype.slice.call(arguments).reduce((t, n) => t + n, 0); } as an arrow function that returns 0 when called with no arguments.
Show answer
const sumAll = (...nums) => nums.reduce((t, n) => t + n, 0); The rest parameter is a real array, so no slice conversion is needed. It is empty when there are no arguments, and reduce with the initial value 0 returns 0.
Exercise
A teammate writes function init({ debug = false }) { return debug; } and calls init(). What happens, and what is the one-character-group fix?
Show answer
It throws a TypeError, because the argument is undefined and destructuring undefined fails. Add a default for the whole parameter: function init({ debug = false } = {}). Then init() returns false.