The ability to define default values for function parameters can make a function easier to use. Default parameter values allow callers to specify
as many or as few arguments as they want while getting the same functionality and minimizing boilerplate, wrapper code.
But all function parameters with default values should be declared after the function parameters without default values. Otherwise, it makes it
impossible for callers to take advantage of defaults; they must re-specify the defaulted values or pass undefined
in order to "get to"
the non-default parameters.
Noncompliant Code Example
function multiply(a = 1, b) { // Noncompliant
return a*b;
}
var x = multiply(42); // returns NaN as b is undefined
Compliant Solution
function multiply(b, a = 1) {
return a*b;
}
var x = multiply(42); // returns 42 as expected
Exceptions
When writing Redux reducers, there is a convention to use default argument syntax to provide initial state (first argument), while action (second
argument) is mandatory. A reducer may be called with undefined
as the state value when the application is being initialized.
// Use the initialState as a default value
export default function appReducer(state = initialState, action) {
switch (action.type) {
default:
return state;
}
}
See