Glossary / Default parameters
Default parameters
Default parameters assign a fallback when a function argument is omitted or explicitly passed as undefined. They make optional inputs visible in a signature and avoid manual checks for undefined. Defaults are evaluated when the call occurs, not when the function is defined.
Trigger conditions and scope
function connect(host = "localhost", port = 8080) {
return `${host}:${port}`;
}
connect(undefined, 3000); // "localhost:3000"
connect(null, 3000); // "null:3000"
A default does not apply to null, false, 0, or empty string. If the desired condition is “nullish,” normalize explicitly with ??; if it is “any falsy value,” || may be appropriate but often masks valid input. Initializers can reference earlier parameters but not later parameters, and parameter initializers have their own environment rules. Defaults may call functions and produce effects, so prefer simple deterministic expressions.
For an optional configuration object, this is common:
function render({ theme = "light" } = {}) { /* ... */ }
The outer = {} handles an omitted/undefined argument; the inner default handles a missing/undefined theme. It still throws if passed null, so validation or explicit null handling may be needed. A default parameter changes the function’s length property: only parameters before the first default are counted.
Interview questions
- What triggers a default parameter? An omitted argument or an argument whose value is undefined.
- Does null trigger it? No.
- Are defaults evaluated once? No; they are evaluated on each call when needed.
- Why use both
{}and an inner default in object parameters? The outer default handles missing options; the inner default handles an absent field.