JavaScript’s default parameters allow you to set a default value in case no value, or an undefined value, is provided when calling a function. This can be useful to avoid errors and make your code more concise.
- To define a default parameter, you can assign a value to the parameter in the function declaration. Here’s an example:
function greet(name = "Anonymous") {
console.log("Hello, " + name );
}
greet(); // Output: Hello, Anonymous
If you call the function without providing an argument for the name
, it will use the default value.
- However, if you pass a value when calling the function, it will override the default value:
function greet(name = "Anonymous") {
console.log("Hello, " + name + "!");
}
greet("John"); // Output: Hello, John!
Here we passed the value of the name and it overrides the default value.
- We can use the return value of a function as a default value for a parameter:
let taxRate = () => 0.1;
let getPrice = function( price, tax = price * taxRate() ) {
return price + tax;
}
let fullPrice = getPrice(100);
console.log(fullPrice); //Output 110