When a function is invoked without passing an argument, the default value is utilized. Moreover, setting the default parameter values can make code more robust, simpler, and easier to read and understand, especially when dealing with optional parameters.
This blog will describe the procedure for setting the parameter’s default value for a function in JavaScript.
How to Set a Default Parameter Value for a JavaScript Function?
To set the default parameter value for a function in JavaScript, use the “=” operator in the function definition.
Syntax
For setting the default parameter value to a function, use the following syntax:
//....
}
Example
Define a function “sum” with three parameters “a”, ”b” and “c” and setting the default parameter values to “7”, “2”, ”4”, respectively:
return a + b + c;
}
Call the defined function “sum()” without passing any arguments. It will give the sum of the default values of parameters:
Now, we will overwrite the default values by passing “1”, “4”, and “6” as arguments. It will return the sum of these provided arguments:
Here, pass the arguments “4” and “3”, which act as a value of the variables “a” and “b”. For “c”, the default value will be used:
Output
You can also set the default value of the parameter inside the function body by identifying whether the type of variable is undefined. If yes, then set the default value of that variable:
if (typeof a === 'undefined') a = 9;
return a + b + c;
}
Call the function that will give the sum of all the default values of “a”, “b”, and “c” which are “9”, “2” and “4” respectively:
Overwrite the values of the parameters and find the sum of all these arguments:
Output
That’s all about setting the default parameter value for JavaScript function.
Conclusion
For setting the default parameter value for a function in JavaScript, use the “=” operator in the function definition. These default values are used at the time of calling the function where the arguments are not passed. You can also set the default values inside the function body. This blog described the procedure for setting the default parameter value for a function in JavaScript.