Default Parameters
In JavaScript, you can specify default values for function parameters right in the function signature. This is particularly useful for optional parameters, ensuring that the function has a safe fallback value if the caller forgets to provide one.
Syntax
Default parameter values are set using the = operator in the function declaration.
function getGreeting(email, name = "there") {
console.log(`Hello ${name}, welcome! Email: ${email}`);
}
// Providing both arguments
getGreeting("lane@example.com", "Lane");
// Output: Hello Lane, welcome! Email: lane@example.com
// Omitting the second argument triggers the default
getGreeting("lane@example.com");
// Output: Hello there, welcome! Email: lane@example.com
Parameter Ordering
A best practice is to place all mandatory parameters at the beginning of the function signature, and all optional parameters (those with default values) at the end. This prevents ambiguity when calling the function.
Practical Example
When creating a user contact profile, a system might require a phone number but consider the name and avatar image optional.
// 'name' and 'avatar' have safe default fallbacks
function createContact(phoneNumber, name = "Anonymous", avatar = "default.jpg") {
if (!phoneNumber) {
return "Invalid phone number";
}
const avatarPath = `/public/pictures/${avatar}`;
return `Contact saved! Name: ${name}, Phone: ${phoneNumber}, Avatar: ${avatarPath}`;
}
console.log(createContact("555-1234"));
// Output: Contact saved! Name: Anonymous, Phone: 555-1234, Avatar: /public/pictures/default.jpg