Dependent defaults
Derive a missing argument from a preceding parameter, such as constructing a label from an earlier value.
JS Puzzles · Const
Default parameter initializers run in their own scope, outside the function body. Earlier parameters are visible, but declarations in the body are not and can cause a runtime ReferenceError.
A default parameter initializer is evaluated when its argument is omitted or undefined. Initializers have a separate scope outside the function body: earlier parameters are available, but body declarations are not, so referencing one raises ReferenceError.
function name(parameter = expression) { /* body */ }function greet(name = makeName()) {
return `Hello, ${name}`;
function makeName() {
return "Ada";
}
}
try {
console.log(greet());
} catch (error) {
console.log(error.name);
}The initializer cannot access declarations in the function body, so calling greet without an argument throws ReferenceError.
Derive a missing argument from a preceding parameter, such as constructing a label from an earlier value.
Recognize why a helper declared inside the body cannot be called from a parameter fallback.
Default parameter initializers run in a scope separate from the function body. That scope is the parent of the body scope, so body declarations are not visible while an initializer is evaluated.
Follow-up: Can an initializer use an earlier parameter? Yes. Parameters are processed left to right, so an earlier parameter is available to a later initializer.
Yes, an initializer may refer to parameters declared earlier in the parameter list. Parameters are initialized from left to right, making those earlier bindings available.
Follow-up: What happens if it refers to a later parameter? The later parameter has not been initialized yet, so the reference fails during evaluation.
A function or variable declared in the function body cannot be referenced by a default initializer. Such a reference causes a runtime ReferenceError, including references to var declarations.
Follow-up: Can the initializer call a function declared outside the function? Yes, outer-scope bindings remain accessible through normal lexical scope lookup.
default parametersfunction bodyfunction scopeparameter initializersReferenceError