Explain JavaScript Default Parameters
In JavaScript, default parameters allow you to initialize function parameters with default values if no value or undefined is passed. This feature helps to avoid undefined values and makes the code more concise and readable.
Here's a simple example to illustrate default parameters in JavaScript:
function greet(name = 'Guest') {
console.log(`Hello, ${name}!`);
}
greet(); // Output: Hello, Guest!
greet('Alice'); // Output: Hello, Alice!
In this example, the greet function has one parameter name with a default value of 'Guest'. If the function is called without an argument or with undefined, the default value 'Guest' is used.
Let's see a more complex example with multiple parameters:
function createUser(username = 'Anonymous', role = 'User') {
console.log(`Username: ${username}, Role: ${role}`);
}
createUser(); // Output: Username: Anonymous, Role: User
createUser('John'); // Output: Username: John, Role: User
createUser('Jane', 'Admin'); // Output: Username: Jane, Role: Admin
createUser(undefined, 'Moderator'); // Output: Username: Anonymous, Role: Moderator
In this example, the createUser function has two parameters username and role, each with their own default values. When calling the function:
- With no arguments, both default values are used.
- With one argument, only the first parameter is overridden.
- With two arguments, both parameters are overridden.
- By passing
undefined for a parameter, the default value for that parameter is used.
Example with Default Parameters and Functions
Default parameters can also be functions or expressions:
function multiply(a, b = 1) {
return a * b;
}
console.log(multiply(5)); // Output: 5
console.log(multiply(5, 2)); // Output: 10
function sum(a = 1, b = 2, c = 3) {
return a + b + c;
}
console.log(sum()); // Output: 6
console.log(sum(4)); // Output: 9
console.log(sum(4, 5)); // Output: 12
console.log(sum(4, 5, 6)); // Output: 15
In these examples:
- The
multiply function has a default parameter b set to 1. If b is not provided, it defaults to 1.
- The
sum function has three parameters, each with their own default values. If not provided, the defaults are used.
Default parameters provide a powerful way to handle optional function arguments and make your code more flexible and robust.