Beginner LevelJavaScript & TypeScript
How do default parameter values work in JavaScript functions?
❓ Interview Prompt: Explain default parameters, evaluation timing, and how undefined vs null affects default parameter substitution.
Default function parameters allow named parameters to be initialized with default values if no value or `undefined` is passed.
Key Rules:
1
Trigger Condition: Defaults only apply when the argument is
undefined or missing.2
`null` does NOT trigger defaults: Passing
null sets the parameter to null!3
Lazy Evaluation: Default expressions are evaluated at call time, not when the function is declared.
4
Earlier Parameters Scope: Later parameters can use the values of preceding parameters:
function f(a, b = a * 2).Code Implementation Example
javascript
function multiply(a, b = 1) {
return a * b;
}
multiply(5, 2); // 10
multiply(5); // 5 (b defaults to 1)
multiply(5, undefined); // 5 (b defaults to 1)
multiply(5, null); // 0 (b becomes null! 5 * null = 0)
// Parameter referencing earlier parameter
function createUser(name, id = Math.random().toString(36).slice(2), role = 'user') {
return { id, name, role };
}💡Default parameter fallback on undefined vs explicit null passing.
🎯 Interview Key Takeaway
Default parameters only evaluate when arguments are undefined or omitted. Explicit null bypasses defaults.
#Functions#Parameters#Defaults#Beginner
Back to all JavaScript & TypeScript Questions→