In this short article we will cover Function Defaults and learn how to use it in our day to day JavaScript programming. This article assumes you have some familiarity with coding in the JavaScript ecosystem.
Function parameters are weird in JavaScript, when you call a function in Java or C# without arguments, you get syntax errors. But when calling a function without providing parameters in JavaScript, your code just runs. This can result to your functions being called with incomplete inputs and that could introduce some bugs. You can counter this problem with defensive programming.
You can add some additional if statements or validations if a function’s parameters have the correct values. But having a lot of if statements for most of your functions could result to messy code. A better way for this is to use the ES6 feature where you can have function defaults. As the example code shows, you can simplify the validation of your function parameters by setting default values.
function sum(x=0, y=0) {
return x + y;
}
console.log(sum());
// expected output: 0
You can also use function defaults one step further by using another parameter as the default. In the code example below, the product() function just squares the first parameter if the second one isn’t provided.
function product(x, y=x) {
return x * y;
}
console.log(product(3));
// expected output: 9
That is all. We used simple examples but we learned how to set sane default values for the parameters in our JavaScript functions, preventing unexpected behavior while keeping the code clean.
Originally published at https://micogongob.com/modern-javascript-function-defaults