How to declare the optional function parameters in JavaScript ?
In this article, we will see how to declare optional function parameters in JavaScript.
These are the following approaches to doing so:
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’:
Javascript
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
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’:
Javascript
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
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.
Javascript
function gfg(a, b) {
if (arguments.length == 0) {
a = "hello" ;
b = "geeks"
}
if (arguments.length == 1) {
b = "geeks" ;
}
return `${a + b}`;
}
console.log(gfg( "hey" ));
|
Last Updated :
13 Dec, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...