Default function parameters
Quick answer
A default parameter supplies a value when the corresponding argument is omitted or explicitly undefined. It does not replace null, zero, false or empty text.
How it works
Use function f(a = 10, b = a + 1). Initializers are evaluated at call time, from left to right; an earlier parameter can be referenced by a later default.
function fee(n = 5) { return n; }console.log(fee(), fee(undefined), fee(0), fee(null));Expected output in Node.js:
5 5 0 nullOnly omitted or undefined arguments activate the default.
function cost(q = 2, price = q * 3) { return q * price; }console.log(cost(), cost(4), cost(4, 2));Expected output in Node.js:
12 48 8The price initializer uses the current q unless price is provided.
Common mistakes
Do not use value || fallback to model default parameters: it also replaces zero and empty strings.
Practice
Predict calls using omitted, undefined and null values.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Default function parameters — Knowledge Check
Apply the taught concept and reason about the result.
What does function f(n=8){return n;} called as f(undefined) return?
What does function f(n=8){return n;} called as f(null) return?
What does function f(n=8){return n;} called as f(0) return?
What does function f(a=2,b=a+1){return b;} called as f(5) return?
When is a default parameter expression evaluated?