Default parameters in functions allow you to initialize function parameters with default values if no arguments are provided during the function call. This feature enhances the flexibility of functions, making them easier to use and reducing the need for additional checks within the function body. Default parameters were introduced in ES6 (ECMAScript 2015) and have become a standard practice in modern JavaScript development.
Using default parameters can simplify your code, improve readability, and help avoid errors that arise from undefined values. Below, we will explore how to use default parameters effectively, along with practical examples, best practices, and common mistakes to avoid.
To define a default parameter, you simply assign a value to the parameter in the function declaration. Here is a basic example:
function greet(name = 'Guest') {
return `Hello, ${name}!`;
}
console.log(greet()); // Output: Hello, Guest!
console.log(greet('Alice')); // Output: Hello, Alice!
In this example, the function `greet` has a default parameter `name` set to 'Guest'. If no argument is provided when calling the function, 'Guest' is used as the default value.
Consider a function that calculates the area of a rectangle. You can use default parameters to set a default value for the width:
function calculateArea(length, width = 5) {
return length * width;
}
console.log(calculateArea(10)); // Output: 50
console.log(calculateArea(10, 2)); // Output: 20
In this example, if the width is not provided, it defaults to 5, making the function versatile for different use cases.
Default parameters can also be useful when merging objects. Here’s an example:
function mergeOptions(defaults, options = {}) {
return { ...defaults, ...options };
}
const defaultOptions = { color: 'blue', size: 'medium' };
const userOptions = { size: 'large' };
console.log(mergeOptions(defaultOptions, userOptions));
// Output: { color: 'blue', size: 'large' }
In this case, if the `options` parameter is not provided, it defaults to an empty object, ensuring that the spread operator works correctly without throwing an error.
function example(param = 'default') {
console.log(param);
}
example(undefined); // Output: 'default'
example(); // Output: 'default'
function example(param = 'default') {
console.log(param);
}
example(null); // Output: null
function example(param = {}) {
param.newProp = true;
console.log(param);
}
example(); // Output: { newProp: true }
example(); // Output: { newProp: true } - Same object reference!
In conclusion, default parameters are a powerful feature in JavaScript that can simplify function definitions and enhance code readability. By following best practices and avoiding common pitfalls, you can leverage default parameters effectively in your projects.