The Wayback Machine - https://web.archive.org/web/20211021030451/https://www.geeksforgeeks.org/how-to-declare-the-optional-function-parameters-in-javascript/
Skip to content
Related Articles

Related Articles

Improve Article

How to declare the optional function parameters in JavaScript ?

  • Last Updated : 10 Jun, 2019
Geek Week

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:

Hey geek! The constant emerging technologies in the world of web development always keeps the excitement for this subject through the roof. But before you tackle the big projects, we suggest you start by learning the basics. Kickstart your web development journey by learning JS concepts with our JavaScript Course. Now at it’s lowest price ever!




My Personal Notes arrow_drop_up
Recommended Articles
Page :