56 lines
1.7 KiB
Plaintext
56 lines
1.7 KiB
Plaintext
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
|
|
|
|
[source,javascript]
|
|
----
|
|
function multiply(a = 1, b) { // Noncompliant
|
|
return a*b;
|
|
}
|
|
|
|
var x = multiply(42); // returns NaN as b is undefined
|
|
----
|
|
|
|
== Compliant Solution
|
|
|
|
[source,javascript]
|
|
----
|
|
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.
|
|
|
|
[source,javascript]
|
|
----
|
|
// Use the initialState as a default value
|
|
export default function appReducer(state = initialState, action) {
|
|
switch (action.type) {
|
|
default:
|
|
return state;
|
|
}
|
|
}
|
|
----
|
|
=== See
|
|
|
|
* https://redux.js.org/tutorials/fundamentals/part-3-state-actions-reducers#writing-reducers[Writing Reducers] - Redux documentation
|
|
|
|
ifdef::env-github,rspecator-view[]
|
|
|
|
'''
|
|
== Implementation Specification
|
|
(visible only on this page)
|
|
|
|
include::message.adoc[]
|
|
|
|
endif::env-github,rspecator-view[]
|