60 lines
2.0 KiB
Plaintext
60 lines
2.0 KiB
Plaintext
== Why is this an issue?
|
|
|
|
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, making a function easier to use.
|
|
|
|
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++`` to be able to specify the non-default parameters.
|
|
|
|
[source,javascript,diff-id=1,diff-type=noncompliant]
|
|
----
|
|
function multiply(a = 1, b) { // Noncompliant: parameter with default value should be last
|
|
return a*b;
|
|
}
|
|
|
|
let x = multiply(1, 42); // Cannot benefit from default value
|
|
----
|
|
|
|
Reorder the function parameters so that the ones with default values come after the ones without default values.
|
|
|
|
[source,javascript,diff-id=1,diff-type=compliant]
|
|
----
|
|
function multiply(b, a = 1) {
|
|
return a*b;
|
|
}
|
|
|
|
let x = multiply(42);
|
|
----
|
|
|
|
=== 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.
|
|
|
|
[source,javascript]
|
|
----
|
|
// Use the initialState as a default value
|
|
export default function appReducer(state = initialState, action) {
|
|
switch (action.type) {
|
|
default:
|
|
return state;
|
|
}
|
|
}
|
|
----
|
|
|
|
== Resources
|
|
=== Documentation
|
|
|
|
* MDN web docs - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Default_parameters[Default parameters]
|
|
* Redux Documentation - https://redux.js.org/tutorials/fundamentals/part-3-state-actions-reducers#writing-reducers[Writing Reducers]
|
|
|
|
ifdef::env-github,rspecator-view[]
|
|
|
|
'''
|
|
== Implementation Specification
|
|
(visible only on this page)
|
|
|
|
=== Message
|
|
|
|
Move parameters "xxx", "yyy" after parameters without default value.
|
|
|
|
|
|
endif::env-github,rspecator-view[]
|