JavaScript(JS) Default Parameter Values

Default parameter values, introduced in ES6 (ECMAScript 2015), allow you to define default values for function parameters in JavaScript. This means that if a parameter is not passed to the function or is passed as undefined, it will be assigned the default value specified in the function definition.

Here's an example of using default parameter values:

ref‮gi:ot re‬iftidea.com
function greet(name = 'World') {
  console.log(`Hello, ${name}!`);
}

greet(); // output: Hello, World!
greet('John'); // output: Hello, John!

In this example, the greet function is defined with a default parameter value of 'World' for the name parameter. If no value is passed for name, it will be assigned the default value of 'World'.

Default parameter values can also reference other parameters, allowing you to create more complex default values:

function calculateTotal(price, tax = 0.1, discount = 0) {
  return (price * (1 - discount)) * (1 + tax);
}

calculateTotal(100); // output: 110
calculateTotal(100, 0.2); // output: 120
calculateTotal(100, 0.2, 0.1); // output: 108

In this example, the calculateTotal function is defined with default parameter values of 0.1 for tax and 0 for discount. The tax parameter references the discount parameter in its calculation, allowing the default value of 0.1 to be used if no value is passed for tax.

Using default parameter values can help simplify function definitions and make it easier to write functions that gracefully handle missing or undefined parameter values.