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
Please Login to comment...