Under the ES6 (ECMAScript 6) standard for JavaScript, a feature named as "Default Parameters" has been introduced that allows developers to assign default values to parameters in a function. This is particularly useful when a function is invoked without passing all the expected arguments, as the parameters with no corresponding arguments will take on their default values.
Here's a very basic example of how the feature can be used:
function greet(name = "Friend") {
return `Hello, ${name}!`;
}
console.log(greet()); // Outputs: Hello, Friend!
console.log(greet("John")); // Outputs: Hello, John!
In this example, when the function greet
is called without any argument, the parameter name
defaults to Friend
. However, if a string is passed as an argument, like "John"
, the function will use that value instead of the default.
While default parameters make functions more flexible and easier to use, there are few best practices one can follow:
Understanding undefined and falsy values: If a function is called with an argument that evaluates to undefined
, the default parameter value will be used. This is unlike other falsy values (like null
, 0
, false
, ''
), which do not trigger the default parameter.
Use defaults for optional parameters: Default parameters are ideal for optional arguments in a function, as it allows you to avoid the typeof
check to see if the argument was provided or not.
Avoid complicated expressions as default values: Try to keep your default parameters simple. If the default value needs to be calculated or is a complex expression, it may be better to handle it inside the body of the function for the sake of clarity.
By understanding and implementing default parameters in ES6, you can write more maintainable and clean JavaScript code.