How do default parameters work in JavaScript functions?
Quick answer
A JavaScript default parameter is used when its argument is omitted or explicitly passed as undefined. Passing null does not use the default: the parameter receives null. Other supplied values are used as given, including values such as 0 or an empty string. For example, in function multiply(a, b = 1), multiply(5) and multiply(5, undefined) both return 5, while multiply(5, null) returns 0. [S1]
The question, the details, the next step.
A practical checklist
Identify which parameter should have a fallback value.
Choose the default and write it in the parameter list, such as
b = 1.Check the behavior when the argument is omitted.
Check the behavior when the caller passes
undefinedandnull.Check ordinary values and any falsy values your function is expected to receive.
A few more useful answers
Does passing `undefined` explicitly behave the same as leaving out the argument?
For a parameter with a default, yes: either omission or an explicit undefined uses the default. [S1]
Will `null` make JavaScript use the default parameter?
No. The parameter receives null; the default is not used. What happens next depends on the function’s operation. [S1]
Does passing `0` trigger a default parameter?
No. A supplied 0 is used as the argument rather than replaced with the default. [S1]
Sources
References used for this guide.
- [S1] Default parameters — JavaScript | MDN developer.mozilla.org · Checked
