How to declare the optional function parameters in JavaScript ?
To declare optional function parameters in JavaScript, there are two approaches:
- 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 on the parameter list.
Syntax:
function myFunc(a,b) { b = b || 0; // b will be set either to b or to 0. }Example 1: In the following program the optional parameter is ‘b’:
<script>function check(a, b) {b = b || 0;document.write("Value of a is: " + a +" Value of b is: " + b +"<br>");}check(5, 3);check(10);</script>chevron_rightfilter_noneOutput:
- 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 on the parameter list.
Syntax:
function myFunc(a, b = 0) { // function body }Example 2: In the following program the optional parameter is ‘b’:
<script>function check(a, b = 0) {document.write("Value of a is: " + a +" Value of b is: " + b +"<br>");}check(9, 10);check(1);</script>chevron_rightfilter_noneOutput:
Recommended Posts:
- JavaScript | Function Parameters
- JavaScript | Passing parameters to a callback function
- JavaScript | Know the value of GET parameters from URL
- Convert URL parameters to a JavaScript Object
- How to serialize an object into a list of URL query parameters using JavaScript ?
- How to declare a global variable in PHP?
- declare command in Linux with Examples
- CSS | optional Selector
- How to get parameters from a URL string in PHP?
- How to avoid NullPointerException in Java using Optional class?
- Perl | Passing Complex Parameters to a Subroutine
- How to call a function that return another function in JavaScript ?
- JavaScript | String() Function
- JavaScript | Function Call
- JavaScript | Math.abs( ) function
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



