Functions
Default parameters
A fallback value for an argument that wasn't passed.
Why it exists
Many arguments are almost always the same: the currency is dollars, the rate is standard, the timeout is 5 seconds. Making every call spell them out is noise. Without defaults a missing argument is undefined, and it had to be "fixed" inside the function: rate = rate || 100. That trick breaks on 0 and the empty string. A default parameter says it right in the function's header — "if not passed, here's the value" — and kicks in only when the argument really is missing.
Where it's used
- Optional settings:
formatPrice(value, currency = "$"). - An options object with defaults:
function request(url, { timeout = 5000, retries = 3 } = {}). - React components:
function Button({ size = "m", variant = "primary" }). - Accumulators in recursive functions:
function sum(list, i = 0).
Syntax
function name(param = value) { … }
function name({ option = value } = {}) { … }Examples
function price(weight, rate = 100) {
return weight * rate;
}
price(3); // → 300function greet(name = "guest") {
return `Hello, ${name}!`;
}
greet(); // → "Hello, guest!"
greet(undefined); // → "Hello, guest!"
greet(null); // → "Hello, null!"undefinedfunction addTag(tag, tags = []) {
tags.push(tag);
return tags;
}
addTag("urgent"); // → ["urgent"]
addTag("fragile"); // → ["fragile"]function connect({ host = "localhost", port = 80 } = {}) {
return `${host}:${port}`;
}
connect(); // → "localhost:80"
connect({ port: 8080 }); // → "localhost:8080"Results after // → aren't just written down — an automatic check runs and verifies them before every site update.
Why it works this way
A default kicks in when the parameter's value is undefined: the argument wasn't passed, or undefined was passed explicitly. null, 0, "" and false are real values and are not replaced.
The default expression is evaluated on every call, not once at declaration. So function add(item, list = []) gets a fresh empty array each time (unlike, say, Python).
Parameters are filled left to right, and a default can use parameters to its left: function f(a, b = a * 2).
Destructured parameters need two levels of defaults: { timeout = 5000 } for a single field, and = {} after the braces for when no object is passed at all. Without = {}, a call with no argument crashes with a TypeError.
Traps
How it differs from…
- Logical operators
!,&&,|| a || bsubstitutesbfor any falsy value —0,"",false. A common source of bugs in old code with defaults.
When to pick something else
Don't hide required data behind a default: if the function makes no sense without the argument (sendEmail(to) with no address), throwing an error beats silently substituting something. And don't make defaults expensive (a server request, a heavy calculation) — they run on every call that omits the argument.