Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

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

  • Last Updated : 11 Oct, 2019

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:

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!




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

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:




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

Output:

10

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




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

Output:

1000



My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!