Sensible Values When the Caller Forgets
JavaScript Default Parameters
Give a parameter a default value with `=`. If the caller doesn't pass that argument, the default kicks in.
What you'll learn
- Set default parameter values
- Know that defaults trigger on `undefined`, not on other falsy values
- Use earlier parameters in later defaults
Default parameters give a parameter a fallback value, used when
the caller doesn’t pass anything (or passes undefined).
function greet(name = "friend") {
console.log(`Hello, ${name}!`);
}
greet("Ada"); // "Hello, Ada!"
greet(); // "Hello, friend!"
greet(undefined); // "Hello, friend!" null Doesn’t Trigger Defaults
Defaults kick in only on undefined (or “no argument”). Passing
null keeps null.
function format(value = "no value") {
console.log(value);
}
format(); // "no value"
format(undefined); // "no value"
format(null); // null ← null is a real value
format(0); // 0 ← so is 0
format(""); // "" ← and "" Earlier Parameters in Later Defaults
Default expressions can reference parameters declared earlier in the list.
function rectangle(width, height = width) {
return width * height;
}
console.log(rectangle(5, 10)); // 50
console.log(rectangle(5)); // 25 ← square, height defaults to width Defaults Can Be Expressions
The default isn’t limited to literals — it can be any expression.
let nextId = 1;
function makeUser(name, id = nextId++) {
return { id, name };
}
console.log(makeUser("Ada")); // { id: 1, name: 'Ada' }
console.log(makeUser("Lin")); // { id: 2, name: 'Lin' }
console.log(makeUser("Tim", 99)); // { id: 99, name: 'Tim' } ← default skipped The default is evaluated only when needed, not at function definition time.
When NOT To Use Defaults
If “no value” should be an error (a required parameter), don’t silently substitute a default — throw an explicit error so the bug shows up loudly:
function required(name) {
throw new Error(`Missing required parameter: ${name}`);
}
function fetchUser(id = required("id")) {
console.log("fetching user", id);
}
fetchUser(42);
// "fetching user 42"
// fetchUser();
// Error: Missing required parameter: id Try It Yourself
Exercise
A greeting with a default
// declare greet here
console.log(greet("Ada"));
console.log(greet());
💡 Show hint
✅ Show solution
function greet(name = "friend") {
return `Hello, ${name}!`;
}
console.log(greet("Ada"));
console.log(greet());
Up Next
What about variable-length argument lists? Rest and spread.
JavaScript Rest & Spread →