- In JavaScript, default parameters or default arguments are a feature that allows you to specify a default value for a function parameter in case no argument is passed or if the argument passed is undefined.
- To define a default parameter in JavaScript, you can simply assign a value to the parameter in the function declaration. Here is an example:
function greet(name = "friend") {
console.log(`Hello, ${name}!`);
}
greet(); // logs "Hello, friend!"
greet("Alice"); // logs "Hello, Alice!"
- In this example, the greet() function has a single parameter name with a default value of "friend". If the function is called with no arguments, the default value is used. If an argument is passed, the argument value is used instead of the default.
- Default parameters are particularly useful when you have optional parameters in a function and want to avoid dealing with undefined values. You can set a default value to those parameters and ensure the function won't break if those parameters are not provided. Additionally, if a value is provided, the function can still use it, overriding the default value.
No comments:
Post a Comment