Provide Fallbacks
Default parameters set a value when an argument is undefined.
They reduce boilerplate checks inside your function.
JavaScript Tutorial
Default parameters let you assign fallback values when arguments are missing.
They simplify functions and reduce manual checks inside the body.
Functions often accept optional inputs. Defaults make those cases clean and predictable.
They also make function signatures more self-documenting.
function name(param = defaultValue) { ... }function greet(name = "Guest") {
return "Hello " + name;
}
console.log(greet());Missing arguments use the default value.
function addTax(price, rate = 0.18) {
return price + price * rate;
}
console.log(addTax(100));Defaults work with any type.
Default parameters set a value when an argument is undefined.
They reduce boilerplate checks inside your function.
Defaults are helpful for configuration objects and optional inputs.
They keep function signatures clean and easy to read.
Default values are evaluated at call time, not at function creation time.
You can even use earlier parameters to compute defaults.
function makeId(prefix, id = prefix + "-" + Date.now()) {
return id;
}
console.log(makeId("user"));Defaults can depend on earlier parameters.
function label(status = "pending") {
return status;
}
console.log(label(null)); // null, not default
console.log(label(undefined)); // uses defaultDefaults only apply when the argument is undefined.
Without
function greet(name) {
if (name === undefined) {
name = "Guest";
}
return "Hello " + name;
}With
function greet(name = "Guest") {
return "Hello " + name;
}Defaults apply only to undefined, not null.
Use defaults for optional values, not required inputs.
Keep defaults simple or move logic into the function body.
When the argument is undefined.
No, null is treated as a real value.
Yes, they are evaluated at call time.
Practice: Create a function that formats currency with a default symbol.
// TODO: function format(amount, symbol = "$")
One Possible Solution
function format(amount, symbol = "$") {
return symbol + amount.toFixed(2);
}
console.log(format(10));Only when the argument is undefined.
Yes, as long as the referenced param appears earlier.
Yes, you can provide defaults in destructured params.
Try calling the function with and without arguments.