JavaScript Functions - Default Parameters


Default parameters in JavaScript functions allow you to set default values for function parameters in case a value is not provided when the function is called. This feature enhances the flexibility and robustness of your functions. In this guide, we'll explore how to use default parameters with practical examples to illustrate their usage.


Basic Usage of Default Parameters


You can set default values for function parameters by assigning them in the function declaration. If a value is not provided when the function is called, the default value will be used. Here's an example:


function greet(name = 'Guest') {
console.log(`Hello, ${name}!`);
}
greet(); // Outputs: "Hello, Guest!"
greet('Alice'); // Outputs: "Hello, Alice!"

In this example, the greet function has a default parameter name set to 'Guest'. When called with no argument, the default value is used.


Default Parameters with Expressions


You can use expressions as default parameter values. This allows you to set dynamic default values. Here's an example:


function calculateTotal(price, taxRate = 0.1, discount = 0) {
const total = price + (price * taxRate) - discount;
return total;
}
console.log(calculateTotal(100)); // Outputs: 100 + (100 * 0.1) - 0 = 110
console.log(calculateTotal(200, 0.15, 10)); // Outputs: 200 + (200 * 0.15) - 10 = 205

In this example, the calculateTotal function has default parameters for taxRate and discount with dynamic default values based on expressions.


Skipping Default Parameters


If you want to use the default value for one parameter but specify values for subsequent parameters, you can do so by passing undefined for the parameter you want to use the default for. Here's an example:


function createMessage(sender, recipient = 'Guest', message) {
console.log(`From: ${sender}, To: ${recipient}, Message: ${message}`);
}
createMessage('Alice', undefined, 'Hello there!'); // Outputs: "From: Alice, To: Guest, Message: Hello there!"

In this example, we specify values for the sender and message parameters while using the default value for recipient

Conclusion


Default parameters are a powerful feature that simplifies function handling, especially when you want to provide fallback values or handle missing arguments gracefully. They enhance the usability and robustness of your functions, making them more versatile in various scenarios.


Happy coding with default parameters in JavaScript functions!