Default Parameter Values
You'll learn: how to give function parameters fallback values so your code doesn't break when arguments are missing.
Why Default Values?
When you call a function without passing all the expected arguments, those missing parameters become undefined. This can cause errors or unexpected behavior. Default parameter values let you specify what a parameter should be if nothing is passed.
Think of it like ordering coffee: if you don't specify sugar, the barista might have a default setting (like "no sugar") rather than leaving it undefined and making a mistake.
The Syntax
You assign a default value directly in the parameter list using =:
function greet(name = "Guest") {
return "Hello, " + name + "!";
}
console.log(greet("Alice")); // "Hello, Alice!"
console.log(greet()); // "Hello, Guest!"
When greet() is called without an argument, name automatically becomes "Guest" instead of undefined.
Multiple Defaults
You can use defaults for any or all parameters:
function createUser(username = "Anonymous", role = "user") {
return username + " is a " + role;
}
console.log(createUser("Bob", "admin")); // "Bob is a admin"
console.log(createUser("Bob")); // "Bob is a user"
console.log(createUser()); // "Anonymous is a user"
When Defaults Trigger
Defaults activate when the argument is undefined or completely omitted. Passing null, 0, false, or an empty string will not trigger the default—only undefined does.
function test(value = 10) {
return value;
}
console.log(test(undefined)); // 10
console.log(test(0)); // 0 (not 10!)
Key Takeaway: Default parameter values provide automatic fallback behavior for missing or undefined arguments, making functions more robust and easier to use.