Mastering Optional Function Parameters in JavaScript: Default Parameters vs. Logical OR
- Default parameters (introduced in ES6): This is the most recommended and modern approach. You can assign a default value to a parameter during function definition. If no value is provided when calling the function, the default value is used.
Here's an example:
function greet(name = "Guest") {
console.log(`Hello, ${name}!`);
}
greet(); // Output: Hello, Guest!
greet("foo"); // Output: Hello, foo!
- Logical OR operator (||) (compatible with older versions of JavaScript): You can use the logical OR operator (||) to assign a default value to a parameter. The function checks if the parameter is truthy (not
undefined
ornull
). If it's falsy, the default value is assigned.
function greet(name) {
name = name || "Guest";
console.log(`Hello, ${name}!`);
}
greet(); // Output: Hello, Guest!
greet("bar"); // Output: Hello, bar!
Choosing the right approach:
- Default parameters (ES6+) are generally preferred as they are more concise and readable.
- Logical OR operator can be used for backward compatibility with older browsers that don't support ES6 features. However, it can be less readable and might lead to unexpected behavior if you want to allow the argument to be explicitly set to
false
ornull
.
Additional considerations:
- You can only use default parameters for the last parameters in a function.
- Default parameters are evaluated at function definition time, not at every function call. This means that if a variable used in the default value changes, it won't affect the default value used in subsequent calls.
javascript function arguments