36 lines
1.0 KiB
Plaintext
Raw Normal View History

2020-06-30 12:47:33 +02:00
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.
2021-02-02 15:02:10 +01:00
2021-01-27 13:42:22 +01:00
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.
2020-06-30 12:47:33 +02:00
== Noncompliant Code Example
2022-02-04 17:28:24 +01:00
[source,javascript]
2020-06-30 12:47:33 +02:00
----
function multiply(a = 1, b) { // Noncompliant
return a*b;
}
var x = multiply(42); // returns NaN as b is undefined
----
== Compliant Solution
2022-02-04 17:28:24 +01:00
[source,javascript]
2020-06-30 12:47:33 +02:00
----
function multiply(b, a = 1) {
return a*b;
}
var x = multiply(42); // returns 42 as expected
----
ifdef::env-github,rspecator-view[]
'''
== Implementation Specification
(visible only on this page)
include::message.adoc[]
endif::env-github,rspecator-view[]