Lessons · JavaScript · default parameters
A default when the argument is missing
function f(x = 5) uses 5 only when x is undefined: missing, or passed as undefined. null and 0 are real values and are kept.
Hone is a place to practise programming. This is one of its lessons, written out in full and free to read without an account.
What it is for
Optional settings, page sizes, retry counts: defaults keep call sites short, and knowing that null does not trigger them prevents a whole class of 'why is it null' bugs.
How to think about it
Put defaults in the signature rather than with || inside the body, which would wrongly replace 0. Expect null to pass through untouched; if null should also default, use ?? in the body.
Worked example
function f(x = 5) { return x; }A default of 5.console.log(f(), f(undefined));5 5: only undefined triggers the default.
console.log(f(null), f(0));null 0: real values, even falsy ones, are kept.
Your turn
Greet with a fallback name.
function greet(name = "") { return "hi " + name; }Solve one with the tests running
The trap
A default expression runs on each call, so x = [] gives a fresh array every time. Unlike Python, nothing is shared between calls.