How to set a default parameter value for a JavaScript function ?

Let us first take a look at a problem and then we’ll take a look at how default values for function parameters address that problem.
Let’s first create a simple function.
Example 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

<script>
    /* This function is simply going to
        multiply two numbers that are passed in*/
    var multiplyIt = function(num1, num2) {
  
        // So we are returning num1 times num2
        return (num1 * num2);
    };
  
    /* Now lets see what happens if we call the 
    above function without passing anything in*/
    console.log(multiplyIt()); 
</script>

chevron_right


This statement would generate an error in some languages but in JavaScript, it is allowed. So basically, the function is going to multiply undefined by undefined.

Output:



NaN 

Because the function is trying to multiply two things that are not a number.

Traditionally, you would pass values in the function but it is much simpler to establish a default value and you do it as a part of the parameters in the function.
Example 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

<script>
    
    //These values will only be taken if a value is not passed in
    var multiplyIt = function(num1 = 2, num2 = 5) 
        {
            return (num1 * num2);
        };
    console.log(multiplyIt()); 
</script>

chevron_right


Output:

10

Example 3: Now try by putting in values 10 and 100.

filter_none

edit
close

play_arrow

link
brightness_4
code

<script>
    
    //In this case, these values will not be considered
    var multiplyIt = function(num1 = 2, num2 = 5) 
        {
            return (num1 * num2);
        };
    console.log(multiplyIt(10, 100));
  
</script>

chevron_right


Output:

1000


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

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.