Sub topic 3
Giving Parameters Default Values
This chapter assumes you can declare and call functions, use let and const, and read template literals. It also builds on the previous chapter: a parameter with no matching argument is undefined.
A default parameter value is a fallback written directly in the parameter list. When the caller leaves the argument out, the parameter gets the fallback instead of undefined. This chapter covers the syntax, the older patterns it replaced, where defaults can appear, and the errors people commonly make with them. Later chapters cover the finer rules: exactly which values trigger a default, when the default expression runs, and what it can refer to.
The Syntax
You write a default with = after the parameter name:
function greet(name = "guest", greeting = "Hello") {
return `${greeting}, ${name}!`;
}
console.log(greet()); // "Hello, guest!"
console.log(greet("Ana")); // "Hello, Ana!"
console.log(greet(undefined, "Hi")); // "Hi, guest!"
console.log(greet(null)); // "Hello, null!"Each parameter is handled on its own. In greet("Ana"), name gets the argument and greeting falls back to "Hello". The last line shows that null counts as a real argument and is not replaced. The next chapter explains why.
The same syntax works in every kind of function:
const square = (x = 1) => x * x;
const counter = {
step(by = 1) {
return by;
},
};
class Timer {
constructor(seconds = 60) {
this.seconds = seconds;
}
}
console.log(square()); // 1
console.log(counter.step()); // 1
console.log(new Timer().seconds); // 60
console.log(new Timer(10).seconds); // 10An arrow function with a default needs parentheses around its parameters, even if there is only one. x = 1 => x * x is a syntax error.
How a Parameter Gets Its Value
When a function is called, JavaScript fills in the parameters from left to right. A parameter that has a default checks the argument in its position. If that argument is missing or undefined, the parameter gets the default.
What Defaults Replaced
Before ES2015, developers wrote fallbacks inside the function body. You will still see these patterns in older code, so you should recognize them and know their flaws.
function oldGreetOr(name) {
name = name || "guest";
return `Hello, ${name}!`;
}
function oldGreetTypeof(name) {
if (typeof name === "undefined") {
name = "guest";
}
return `Hello, ${name}!`;
}
console.log(oldGreetOr("")); // "Hello, guest!" (empty string was thrown away)
console.log(oldGreetTypeof("")); // "Hello, !"The || version is short, but it replaces every falsy value, including 0, "", false, and NaN. That is a real bug when those values are valid input:
function setVolumeOld(level) {
level = level || 50;
return level;
}
function setVolume(level = 50) {
return level;
}
console.log(setVolumeOld(0)); // 50, the caller asked for mute and got 50
console.log(setVolume(0)); // 0The typeof check is correct but wordy, and the fallback sits in the body where readers might not see it. A default parameter is correct and also documents the fallback in the function signature.
| Pattern | Replaces `undefined` | Replaces `0`, `""`, `false` | Visible in signature | Column | Column |
|---|---|---|---|---|---|
| `x = x \ | \ | fallback` | Yes | Yes (often a bug) | No |
| `if (typeof x === "undefined")` | Yes | No | No | ||
| `x = x ?? fallback` | Yes | No (also replaces `null`) | No | ||
| `function f(x = fallback)` | Yes | No | Yes |
Defaults Can Be Any Expression
A default does not have to be a literal. Any expression is allowed: a function call, an object, an array, or a template literal.
function makeId() {
return Math.random().toString(36).slice(2, 8);
}
function createTask(title = "Untitled", id = makeId(), tags = []) {
return { id, title, tags };
}
const task = createTask("Write docs");
console.log(task.title); // "Write docs"
console.log(typeof task.id); // "string"
console.log(task.tags.length); // 0The makeId() call only runs when id actually needs its default. If the caller passes an id, makeId is never called. Later chapters build on this when they look at how and when defaults are evaluated.
Defaults in the Middle of the List
Defaults do not have to come last, but a default on a non-final parameter is awkward to use. Arguments match by position, so the caller cannot skip a slot. They have to pass undefined explicitly:
function range(start = 0, end) {
const out = [];
for (let i = start; i < end; i++) out.push(i);
return out;
}
console.log(range(2, 5)); // [2, 3, 4]
console.log(range(undefined, 3)); // [0, 1, 2]
console.log(range(3)); // [] because start = 3 and end is undefinedrange(3) is the common mistake. The caller meant "up to 3", but the 3 lands in start, and i < undefined is always false. Put parameters with defaults after the required ones. When a function has several optional settings, use an options object instead. A later chapter covers that pattern.
Common Errors
| Mistake | What happens | Fix | Column | Column |
|---|---|---|---|---|
| Using `\ | \ | ` for fallbacks | `0`, `""`, `false` are replaced | Use a default parameter |
| Default before a required parameter | Callers must pass `undefined` | Move optional parameters to the end | ||
| `x = 1 => ...` arrow syntax | Syntax error | Write `(x = 1) => ...` | ||
| Expecting `null` to trigger the default | `null` is kept | Pass `undefined`, or handle `null` explicitly |
Exercise
What does each call log? function pad(text, width = 8, char = " ") { return text.padStart(width, char); } console.log(pad("42")); console.log(pad("42", 5, "0")); console.log(pad("42", undefined, "*"));
Show answer
" 42" (six spaces then 42, width 8), "00042", and "*42". In the third call the explicit undefined makes width fall back to 8, while char is "".
Exercise
Rewrite this function using default parameters, and explain which call changes its result: function tax(amount, rate) { rate = rate || 0.2; return amount * rate; } called as tax(100, 0).
Show answer
function tax(amount, rate = 0.2) { return amount * rate; }. With the original, tax(100, 0) returns 20 because 0 is falsy and gets replaced. With the default parameter it returns 0, because only a missing or undefined argument triggers the default.
Exercise
A teammate writes function fetchPage(page = 1, url) { ... } and calls fetchPage("/api/items"). What goes wrong, and how would you fix the signature?
Show answer
The string "/api/items" binds to page and url is undefined, because arguments match by position. Reorder to function fetchPage(url, page = 1) so the required parameter comes first and the optional one can be left out.