Sub topic 6
Using Earlier Parameters in Defaults
This chapter assumes you know how to declare and call functions and how to write a basic default value such as name = "guest". It also assumes you know that a default is used only when the argument is undefined, and that the default expression runs again on every call. Here the question is what a default expression can see: the earlier parameters, the variables around the function, and which names are off limits.
The Basic Rule: Defaults Can Read Parameters to Their Left
A default value can be any expression. That expression can use parameters declared earlier in the same parameter list:
function area(width, height = width) {
return width * height;
}
console.log(area(4)); // 16, height copies width
console.log(area(4, 2)); // 8, height is given explicitlyWhen area(4) runs, width is bound to 4 first. Then height has no argument, so its default width is evaluated, and width already holds 4.
The earlier parameter can be used inside a larger expression too. This is common when one argument describes the size or shape of another:
function slicePart(items, start = 0, end = items.length) {
return items.slice(start, end);
}
function pad(text, width = text.length + 4, fill = " ") {
return text.padStart(width, fill);
}
console.log(slicePart(["a", "b", "c", "d"], 1)); // ["b", "c", "d"]
console.log(pad("hi")); // " hi"
console.log(pad("hi", 5, "*")); // "***hi"Binding Happens Left to Right
Parameters are initialized one at a time, from left to right. For each parameter, JavaScript takes the matching argument. If that argument is undefined and a default exists, it evaluates the default. Only after that does it move on to the next parameter.
So a default can depend on a parameter to its left, because that parameter is already initialized. It cannot depend on a parameter to its right.
Referencing a Later Parameter Throws
Parameters behave much like let bindings. Each one exists from the start of the call but stays in the temporal dead zone until it is initialized. The temporal dead zone is the stretch of time when a name exists but reading it throws a ReferenceError.
function broken(a = b, b = 1) {
return [a, b];
}
console.log(broken(5)); // [5, 1], default for a never runs
console.log(broken(5, 2)); // [5, 2]
try {
broken(); // default for a reads b too early
} catch (err) {
console.log(err.name); // "ReferenceError"
}
try {
broken(undefined, 2); // still fails: b is not initialized yet
} catch (err) {
console.log(err.message); // "Cannot access 'b' before initialization"
}The last call trips people up. You passed 2 for b, but a is processed first, and at that moment b has not been bound yet. Passing a value for b does not change the order.
A parameter cannot refer to itself either. function f(x = x) {} throws a ReferenceError when called without an argument, because x is still in the temporal dead zone while its own default runs.
Defaults Can Also See the Outer Scope
Default expressions can read anything visible where the function is defined: module constants, other functions, and imported values.
const DEFAULT_TIMEOUT = 5000;
function makeId(prefix) {
return `${prefix}-${Math.random().toString(36).slice(2, 8)}`;
}
function request(url, timeout = DEFAULT_TIMEOUT, id = makeId("req")) {
return { url, timeout, id };
}
console.log(request("/api").timeout); // 5000Defaults Cannot See the Function Body
When a function has default values, its parameters live in their own scope, which sits between the outer scope and the function body. Default expressions are evaluated in that parameter scope. Variables declared in the body do not exist yet, and the defaults cannot see them.
const label = "outer";
function show(getLabel = () => label) {
const label = "inner";
return getLabel();
}
console.log(show()); // "outer"The arrow function () => label was created in the parameter scope. Looking up label from there goes to the outer scope, not into the body. The body's const label is a separate variable that the default never sees.
The body can still read and reassign the parameters normally. A var in the body with the same name as a parameter starts with the parameter's value:
function demo(x = 1) {
var x; // separate body variable, initialized from parameter x
console.log(x); // 1
x = 2;
return x;
}
console.log(demo()); // logs 1, then prints 2Using let or const with a parameter's name in the body is a SyntaxError. Plain functions with no defaults have the same restriction, so this is not specific to defaults.
Scope Summary
| Name used in a default | Visible? | What happens |
|---|---|---|
| Parameter to the left | Yes | Reads its bound value |
| The parameter itself | No | `ReferenceError` (temporal dead zone) |
| Parameter to the right | No | `ReferenceError` (temporal dead zone) |
| Outer or module variable | Yes | Normal closure lookup |
| Variable declared in the body | No | Resolves to an outer variable with that name, or throws if none exists |
Design Guidelines
- Put the parameters other parameters depend on first. If
enddefaults toitems.length, thenitemsmust come beforeend. - Keep dependent defaults simple.
height = widthis clear. A default that combines three earlier parameters in a calculation usually belongs in the body, where it can be named and commented. - If two parameters depend on each other, defaults cannot express that. Compute the values in the body, or take an options object.
- Remember that an explicit
nullskips the default.area(4, null)returns0, becausenullis coerced to0in the multiplication.
Exercise
What does each call print? function range(start, end = start + 10, step = end > start ? 1 : -1) { return [start, end, step]; } Calls: range(0), range(5, 2), range(3, undefined, 2).
Show answer
range(0) gives [0, 10, 1]: end defaults to 0 + 10, and since 10 > 0, step is 1. range(5, 2) gives [5, 2, -1]: end is passed, and since 2 is not greater than 5, step is -1. range(3, undefined, 2) gives [3, 13, 2]: undefined triggers end's default 3 + 10, and step is passed explicitly, so its default never runs.
Exercise
Why does function total(price = qty * unit, qty = 1, unit = 10) { return price; } throw when called as total(), and how would you fix it?
Show answer
The default for price runs first, while qty and unit are still in the temporal dead zone, so reading qty throws a ReferenceError. Fix it by reordering so the dependencies come first: function total(qty = 1, unit = 10, price = qty * unit) { return price; }, which returns 10 when called with no arguments.
Exercise
What does this print, and why? let n = 1; function f(get = () => n) { let n = 2; return get(); } console.log(f());
Show answer
It prints 1. The arrow function is created in the parameter scope, so it resolves n in the outer scope. The body's let n = 2 is a separate variable that the default cannot see.