Implementing default values for function parameters
I have seen many different implementations to handle default parameters or default values using different mechanisms for parameters on functions. Since some years JavaScript supports default values for function parameters. Here you see the difference on all 3 methods as overview.
The example will assign a default value of 100 in case ...
Using the logical OR operator
This kind-of old style implementation using the logical OR operator.
// use the OR operator for assigning a default value.
function waittimeOR(duration) {
const d = duration || 100;
return (d);
}
Using the coalescing operator
This operator ...
// use the coalescing operator for assigning a default value.
function waittimeCO(duration) {
const d = duration ?? 100;
return (d);
}
Using the function default values
This mechanism is extending the javascript function declaration syntax by using a ...
// use the coalescing operator for assigning a default value.
function waittimeP(duration = 100) {
const d = duration;
return (d);
}
Results
These are the raw results from the 3 functions above when using the input parameter:
(input) -- (waittimeOR), (waittimeCO), (waittimeP)
Using the OR operator shows problematic when using "falsy" values like a numeric value of '0'. Also paramters are treaded different when passed as strings or as numbers.
The coalescing operator is handling these cases better as it has a better understanding of "given value" that also fits to defaulting falsy parameters. Still `null` parameters are treated like `undefined` parameters.
Using default assignments in the function definition handles `null` parameters different. Here a given `null` value is treated like any given value of another type.
Summary
The mechanism to use for default parameters has to be chosen wisely based on the datatype you expect. The OR method might be good for boolean inputs. If you have explicit `null` value cases the default assignments in the function definitions are the best to be used.
As a general rule check that you don't mix `null`and `undefined` use-cases. Using typescript will warn you as these values also differ by the type definitions. However it will not be checked at runtime.
See also
- https://atomizedobjects.com/blog/javascript/nullish-coalescing-vs-or-javascript-operators/
- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Default_parameters