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:
<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
Recommended Posts:
- Passing a function as a parameter in JavaScript
- How to pass an array as a function parameter in JavaScript ?
- How to get the javascript function parameter names/values dynamically?
- JavaScript | Pass string parameter in onClick function
- How to add a parameter to the URL in JavaScript ?
- JavaScript | Rest parameter
- How to set textarea scroll bar to bottom as a default using JavaScript/jQuery ?
- How to hide div element by default and show it on click using JavaScript and Bootstrap ?
- HTML | DOM Parameter value Property
- Argument vs Parameter in Java
- HTML | DOM Parameter Object
- HTML | DOM Parameter name Property
- Python | file parameter in print()
- C# | Default Constructor
- CSS | :default Selector
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.

