In this article, we will see how to declare optional function parameters in JavaScript.
These are the following approaches to doing so:
Table of Content
Using the Logical OR operator (‘||’)
In this approach, the optional parameter is Logically OR is used with the default value within the body of the function.
Note: The optional parameters should always come at the end of the parameter list.
Syntax:
function myFunc(a,b) {
b = b || 0;
// b will be set either to b or to 0.
}
Example: In the following program the optional parameter is ‘b’:
function check(a, b) {
b = b || 0;
console.log( "Value of a is: " + a +
" Value of b is: " + b);
} check(5, 3); check(10); |
Value of a is: 5 Value of b is: 3 Value of a is: 10 Value of b is: 0
Using the Assignment operator (“=”)
In this approach the optional variable is assigned the default value in the declaration statement itself. Note: The optional parameters should always come at the end of the parameter list.
Syntax:
function myFunc(a, b = 0) {
// function body
}
Example: In the following program the optional parameter is ‘b’:
function check(a, b = 0) {
console.log( "Value of a is: " + a +
" Value of b is: " + b);
} check(9, 10); check(1); |
Value of a is: 9 Value of b is: 10 Value of a is: 1 Value of b is: 0
Using argument variable
In this approach, we are checking the length of the argument and by using if-else we are returning results accordingly.
Example: This exanpmle shows the implementation of the above-explained appraoch.
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" ));
|
heygeeks