DEV Community

Cover image for Default Parameter Value in JavaScript Functions
Md. Fahim Bin Amin
Md. Fahim Bin Amin

Posted on

Default Parameter Value in JavaScript Functions

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);
}
Enter fullscreen mode Exit fullscreen mode

This function simply receives two values as arguments and returns their summation value.

Therefore, we get:

sum(2, 3) // returns 5
Enter fullscreen mode Exit fullscreen mode

sum function

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:

NaN

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);
Enter fullscreen mode Exit fullscreen mode

With default parameter value

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);
Enter fullscreen mode Exit fullscreen mode

all argument values with default parameter value

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)

Collapse
 
jonrandy profile image
Jon Randy πŸŽ–οΈ • Edited

This is not correct at all. The default value for a missing parameter is undefined. Trying to add undefined to a Number will give you NaN.

You can easily see that the missing parameter defaults to undefined:

function add(a, b) {
  console.log(b)
}

> add(5) 

undefined 
Enter fullscreen mode Exit fullscreen mode
Collapse
 
fahimfba profile image
Md. Fahim Bin Amin

Thank you so much. I have corrected the mistake.