Default parameters, introduced in ES6, allow you to initialize named parameters with default values if no value or undefined
is passed during the function call. This makes your functions more robust and predictable.
Example 1: Basic Default Value
// A simple function that greets a user.
// If no name is provided, it defaults to 'Guest'.
function greet(name = 'Guest') {
console.log(`Hello, ${name}!`);
}
greet('Alice'); // Output: Hello, Alice!
greet(); // Output: Hello, Guest!
Explanation
In this example, the name
parameter is assigned a default value of 'Guest'
. When the greet
function is called without an argument, this default value is used.
Example 2: Using Expressions as Defaults
// A function that calculates a total price.
// The tax is calculated based on a default rate of 10%.
function calculateTotal(price, tax = price * 0.10) {
return price + tax;
}
console.log(calculateTotal(100)); // Output: 110
Explanation
The default value for the tax
parameter is an expression that calculates 10% of the price
. This demonstrates that default parameters can be based on other parameters.
Example 3: Default with null
Coalescing
// A function to create a user profile.
// The username defaults to 'Anonymous'.
function createUser(name, username = 'Anonymous') {
return { name, username };
}
console.log(createUser('John Doe')); // Output: { name: 'John Doe', username: 'Anonymous' }
console.log(createUser('Jane Doe', null)); // Output: { name: 'Jane Doe', username: null }
Explanation
Default parameters are only applied when the argument is undefined
, not null
. This shows that passing null
will override the default value.
Example 4: Default Parameters in Arrow Functions
// An arrow function to create a settings object.
// The theme defaults to 'dark'.
const createSettings = (theme = 'dark', notifications = true) => {
return { theme, notifications };
};
console.log(createSettings()); // Output: { theme: 'dark', notifications: true }
Explanation
Default parameters work seamlessly with arrow functions, a concise syntax for writing functions. Here, both theme
and notifications
have default values.
Example 5: Using Functions as Default Values
// A function that throws an error if a parameter is missing.
const required = () => { throw new Error('Parameter is required'); };
// A function to add two numbers, where 'b' is mandatory.
const add = (a = 0, b = required()) => {
return a + b;
};
// add(10); // Throws an error: Parameter is required
console.log(add(10, 5)); // Output: 15
Explanation
A function call can be used as a default value. In this case, the required
function is called if the second argument to add
is not provided, making the parameter mandatory.
Example 6: Destructuring with Default Values
// A function that accepts a configuration object.
// Default values are provided for 'width' and 'height' via destructuring.
function configure({ width = 800, height = 600 } = {}) {
console.log(`Dimensions: ${width}x${height}`);
}
configure({ width: 1024 }); // Output: Dimensions: 1024x600
configure(); // Output: Dimensions: 800x600
Explanation
This example combines destructuring with default parameters. The function expects an object, and if properties are missing, their defaults are used. The = {}
ensures the function doesn't error if called with no arguments.
Example 7: Order of Default Parameters
// A function where a non-default parameter follows a default one.
function createMessage(message = "Default message", sender) {
return `${sender}: ${message}`;
}
console.log(createMessage(undefined, "System")); // Output: System: Default message
Explanation
You can have non-default parameters after default ones. To use the default for message
while providing a value for sender
, you must explicitly pass undefined
for the message
parameter.