Skip to content
Related Articles

Related Articles

How to declare the optional function parameters in JavaScript ?
  • Last Updated : 10 Jun, 2019

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>

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




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

    Output:

full-stack-img

My Personal Notes arrow_drop_up
Recommended Articles
Page :