How to declare the optional function parameters in JavaScript ?
In this article, we will see how to declare optional function parameters in JavaScript. There are two approaches to do so:
Using the Logical OR operator (‘||’): In this approach, the optional parameter is Logically ORed 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’:
html
< script > function check(a, b) { b = b || 0; console.log("Value of a is: " + a + " Value of b is: " + b); } check(5, 3); check(10); </ script > |
Output:
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’:
html
< script > function check(a, b = 0) { console.log("Value of a is: " + a + " Value of b is: " + b); } check(9, 10); check(1); </ script > |
Output:
Value of a is: 9 Value of b is: 10 Value of a is: 1 Value of b is: 0
Please Login to comment...