In JavaScript, we can define default values in the function's parameter to safeguard it from returning NaN.
Let me give you an example of this,
Let's say, we are using a function called sum
:
function sum (a, b) {
return(a + b);
}
This function simply receives two values as arguments and returns their summation value.
Therefore, we get:
sum(2, 3) // returns 5
However, for some reason, if the user does not provide the value of any parameter as an argument, then it becomes NaN as the default value of all the parameters is Undefined in JavaScript.
Therefore, the following scenario can happen:
Here, as we didn't provide the value for the second parameter in the argument, it takes the default value for variable b
as Undefined
. Therefore, 5
+
Undefined
returns NaN
.
However, let's say, we provide a default parameter value for the second variable for now (b
) to ZERO (b = 0), then we get the following output for the same input:
function sum (a, b = 0) {
return(a + b);
}
sum (5);
Here, you see that we have explicitly specified the initial (default) parameter value for the variable b
as 0
. Therefore, if we do not pass any value during function calls, the default argument value for variable b
becomes 0.
As 5
+
0
= 5
, we get 5
as the output.
However, this does not change anything crucial other than safeguarding the function.
If we call the function with all the values in it via arguments, it works flawlessly.
function sum (a, b = 0) {
return(a + b);
}
sum (2, 10);
Here, although the initial (default) value for the second variable was zero (0
), the updated value was 10
which was passed during the function call as argument value. The updated value overwrites the initial/default value. Therefore, all the calculation works seamlessly.
Sometimes, we like to provide default values in all the function parameters if we want to avoid these Undefined
type calculations in the output.
I hope you have learned something new today! Thank you for reading. π
Top comments (2)
This is not correct at all. The default value for a missing parameter is
undefined
. Trying to addundefined
to a Number will give youNaN
.You can easily see that the missing parameter defaults to
undefined
:Thank you so much. I have corrected the mistake.