Default and Rest Parameters
In short: function f(x = 50) {} gives x a default value — but
that default only kicks in when the caller passes undefined or leaves
the argument out entirely; an explicit 0, "", or false is a real
value and is used as-is. function f(first, ...rest) {} uses the rest
parameter to scoop up every argument after the named ones into a genuine
array — it must be the last parameter, since nothing could come after it.
![A form with a pre-filled fallback field: play(80) fills volume = 80; play() leaves it blank and falls back to volume = 50 (default only fires for undefined, play(0) keeps 0, not 50); below, a duffel bag: queue("Blue Hour", "Red Dawn", "Green Tide") gives first = "Blue Hour" and rest = ["Red Dawn", "Green Tide"], a real array](/api/assets/javascript/assets/33cb0f92986f6678.png)
Fall back to a default volume
A default only fills in when the argument is genuinely missing —
undefined, whether from an omitted argument or an explicit one:
play(80) prints 80 — the caller supplied a value, so the default is
never consulted. play() prints 50 — no argument at all means volume
is undefined, which triggers the default. play(0) prints 0, not
50 — 0 is an explicit, real argument, and defaults only ever replace
undefined, exactly the same rule ??= uses for variables.
Gather every extra song into a real array
...rest collects whatever arguments are left after the named
parameters, packaged as an actual array with every array method
available:
first takes the first argument, "Blue Hour". rest, being the final
parameter, absorbs everything after it — ["Red Dawn", "Green Tide"] — as
a real array, so rest.length, rest.map(...) and so on all work
directly, unlike the older arguments object.
Quick practice
What does function play(volume = 50) { console.log(volume); } play(); print?
What does function play(volume = 50) { console.log(volume); } play(0); print?
In function queue(first, ...rest) {}, what type of value is rest inside the function?
What does function queue(first, ...rest) { console.log(rest); } queue("A", "B", "C"); print?
Where must a rest parameter appear in a function's parameter list?
🎯 Your turn
Explain what
function play(volume = 50) { console.log(volume); } play(0);
prints and why, and what
function queue(first, ...rest) { console.log(rest); } queue("A", "B", "C");
prints and why.
Write your explanation and submit it — there's no code to run here, just your reasoning.
