25 lines
874 B
Plaintext
25 lines
874 B
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
|
|
|
|
----
|
|
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
|
|
----
|