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’:

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    <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_right

    
    

    Output:

  • 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’:

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    <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_right

    
    

    Output:



My Personal Notes arrow_drop_up


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.