Declare Optional Function Parameters in JavaScript
Optional parameters in JavaScript let functions work even when some arguments are not provided, making them more flexible and reusable.
- Missing parameters are automatically set to
undefinedor a default value. - You can define default values directly in the function definition.
- Useful for creating functions with flexible behaviour and fewer overloads.
These are the following approaches to doing so:
Using the Logical OR operator ('||')
The Logical OR operator (||) is used to assign a default value to an optional parameter. If the parameter is null, undefined, or falsy, the default value is used instead, ensuring the function works even with missing arguments.
function check(a, b) {
b = b || 0;
console.log("Value of a is: " + a +
" Value of b is: " + b);
}
check(5, 3);
check(10);
Output
Value of a is: 5 Value of b is: 3 Value of a is: 10 Value of b is: 0
Syntax:
function myFunc(a,b) {
b = b || 0;
// b will be set either to b or to 0.
}Note: The optional parameters should always come at the end of the parameter list.
Using the Assignment operator ("=")
The assignment operator (`=`) approach allows you to set default values directly in the function's parameter list. If an argument is not provided, the parameter automatically takes the default value, simplifying the handling of optional parameters in functions.
function check(a, b = 0) {
console.log("Value of a is: " + a +
" Value of b is: " + b);
}
check(9, 10);
check(1);
Output
Value of a is: 9 Value of b is: 10 Value of a is: 1 Value of b is: 0
Syntax
function myFunc(a, b = 0) {
// function body
}Using argument variable
The arguments variable is an array-like object holding all arguments passed to a function. This approach checks the number of passed arguments and assigns default values or handles missing ones based on the argument count, providing flexibility in parameter handling.
function gfg(a, b) {
// No parameters are passed
if (arguments.length == 0) {
a = "hello";
b = "geeks"
}
// Only one parameter is passed
if (arguments.length == 1) {
b = "geeks";
}
return `${a + b}`;
}
console.log(gfg("hey"));
Output
heygeeks
Using Rest Parameters
The rest parameter syntax (...rest) allows you to collect all remaining arguments into an array. This can be particularly useful for functions that can accept a variable number of arguments.
// Function that uses rest parameters to handle optional parameters
function check(a, ...rest) {
let b = rest.length > 0 ? rest[0] : 0;
console.log(`Value of a is: ${a} Value of b is: ${b}`);
}
// Calling the function with both parameters
check(5, 3);
// Calling the function with only the first parameter
check(10);
// Calling the function with more than two parameters
check(1, 2, 3);
Output
Value of a is: 5 Value of b is: 3 Value of a is: 10 Value of b is: 0 Value of a is: 1 Value of b is: 2
Syntax:
function myFunc(a, ...rest) {
// function body
}