Default Parameters
Fallback values.
What happens if you call a function, but forget to pass an argument? The parameter is undefined, which can cause strange results. Default parameters give a fallback value instead.

- Forgot an argument?
- It's undefined
- Defaults give a fallback
Equals in the brackets
Put an equals sign and a value after a parameter's name. If the caller doesn't pass that argument, the default is used. If they do, their value wins. Run it.
function greet(name = "friend", greeting = "Hello") {
return `${greeting}, ${name}!`;
}
console.log(greet());
console.log(greet("Ana"));
console.log(greet("Ben", "Good morning"));Hello, friend! Hello, Ana! Good morning, Ben!
Good defaults
Defaults make functions easier to use, because callers only pass what they need to change. Put parameters with defaults at the end of the list. And choose sensible defaults, the value most callers would want anyway.
| key | value |
|---|---|
| name = 'friend' | a default |
| Not passed | default used |
| Passed | their value wins |
| Order | defaults last |
Defaults that use other parameters
A default can use earlier parameters. Here, the height defaults to the width, so calling with one number makes a square. Defaults only kick in for missing or undefined arguments. Passing zero, or an empty string, keeps that value. Run it.
function box(width, height = width) {
return `${width} by ${height}`;
}
console.log(box(4));
console.log(box(4, 2));
console.log(box(4, undefined));
console.log(box(4, 0));4 by 4 4 by 2 4 by 4 4 by 0
Summary
Default parameters supply a value when an argument isn't passed. Next, a shorter way to write functions.
Key takeaways- param = value
- Used when missing
- Put defaults last