...
)undefined
trigger default values?arguments
!...
)
Parameter handling has been significantly upgraded in ECMAScript 6. It now supports parameter default values, rest parameters (varargs) and destructuring.
Additionally, the spread operator helps with function/method/constructor calls and Array literals.
A default parameter value is specified for a parameter via an equals sign (=
). If a caller doesn’t provide a value for the parameter, the default value is used. In the following example, the default parameter value of y
is 0:
If you prefix a parameter name with the rest operator (...
), that parameter receives all remaining parameters via an Array:
You can simulate named parameters if you destructure with an object pattern in the parameter list:
The = {}
in line A enables you to call selectEntries()
without paramters.
...
) In function and constructor calls, the spread operator turns iterable values into arguments:
In Array literals, the spread operator turns iterable values into Array elements:
The ES6 way of handling parameters is equivalent to destructuring the actual parameters via the formal parameters. That is, the following function call:
is roughly equivalent to:
Example – the following function call:
becomes:
Let’s look at specific features next.
ECMAScript 6 lets you specify default values for parameters:
Omitting the second parameter triggers the default value:
Watch out – undefined
triggers the default value, too:
The default value is computed on demand, only when it is actually needed:
undefined
trigger default values? It isn’t immediately obvious why undefined
should be interpreted as a missing parameter or a missing part of an object or Array. The rationale for doing so is that it enables you to delegate the definition of default values. Let’s look at two examples.
In the first example (source: Rick Waldron’s TC39 meeting notes from 2012-07-24), we don’t have to define a default value in setOptions()
, we can delegate that task to setLevel()
.
In the second example, square()
doesn’t have to define a default for x
, it can delegate that task to multiply()
:
Default values further entrench the role of undefined
as indicating that something doesn’t exist, versus null
indicating emptiness.
Within a parameter default value, you can refer to any variable, including other parameters:
However, order matters. Parameters are declared from left to right. “Inside” a default value, you get a ReferenceError
if you access a parameter that hasn’t been declared, yet:
Default values exist in their own scope, which is between the “outer” scope surrounding the function and the “inner” scope of the function body. Therefore, you can’t access “inner” variables from the default values:
If there were no outer x
in the previous example, the default value x
would produce a ReferenceError
(if triggered).
This restriction is probably most surprising if default values are closures:
Putting the rest operator (...
) in front of the last formal parameter means that it will receive all remaining actual parameters in an Array.
If there are no remaining parameters, the rest parameter will be set to the empty Array:
arguments
! Rest parameters can completely replace JavaScript’s infamous special variable arguments
. They have the advantage of always being Arrays:
One interesting feature of arguments
is that you can have normal parameters and an Array of all parameters at the same time:
You can avoid arguments
in such cases if you combine a rest parameter with Array destructuring. The resulting code is longer, but more explicit:
The same technique works for named parameters (options objects):
arguments
is iterable arguments
is iterable5 in ECMAScript 6, which means that you can use for-of
and the spread operator:
When calling a function (or method) in a programming language, you must map the actual parameters (specified by the caller) to the formal parameters (of a function definition). There are two common ways to do so:
Named parameters have two main benefits: they provide descriptions for arguments in function calls and they work well for optional parameters. I’ll first explain the benefits and then show you how to simulate named parameters in JavaScript via object literals.
As soon as a function has more than one parameter, you might get confused about what each parameter is used for. For example, let’s say you have a function, selectEntries()
, that returns entries from a database. Given the function call:
what do these three numbers mean? Python supports named parameters, and they make it easy to figure out what is going on:
Optional positional parameters work well only if they are omitted at the end. Anywhere else, you have to insert placeholders such as null
so that the remaining parameters have correct positions.
With optional named parameters, that is not an issue. You can easily omit any of them. Here are some examples:
JavaScript does not have native support for named parameters, unlike Python and many other languages. But there is a reasonably elegant simulation: Each actual parameter is a property in an object literal whose result is passed as a single formal parameter to the callee. When you use this technique, an invocation of selectEntries()
looks as follows.
The function receives an object with the properties start
, end
, and step
. You can omit any of them:
In ECMAScript 5, you’d implement selectEntries()
as follows:
In ECMAScript 6, you can use destructuring, which looks like this:
If you call selectEntries()
with zero arguments, the destructuring fails, because you can’t match an object pattern against undefined
. That can be fixed via a default value. In the following code, the object pattern is matched against {}
if the first parameter is missing.
You can also combine positional parameters with named parameters. It is customary for the latter to come last:
In principle, JavaScript engines could optimize this pattern so that no intermediate object is created, because both the object literals at the call sites and the object patterns in the function definitions are static.
You will probably mostly use the for-of
loop in ECMAScript 6, but the Array method forEach()
also profits from destructuring. Or rather, its callback does.
First example: destructuring the Arrays in an Array.
Second example: destructuring the objects in an Array.
An ECMAScript 6 Map doesn’t have a method map()
(like Arrays). Therefore, one has to:
[key,value]
pairs.map()
the Array.This looks as follows.
The tool method Promise.all()
works as follows:
Destructuring helps with handling the Array that the result of Promise.all()
is fulfilled with:
fetch()
is a Promise-based version of XMLHttpRequest
. It is part of the Fetch standard.
This section mentions a few tricks for descriptive parameter definitions. They are clever, but they also have downsides: they add visual clutter and can make your code harder to understand.
Some parameters have no default values, but can be omitted. In that case, I occasionally use the default value undefined
to make it obvious that the parameter is optional. That is redundant, but descriptive.
In ECMAScript 5, you have a few options for ensuring that a required parameter has been provided, which are all quite clumsy:
In ECMAScript 6, you can (ab)use default parameter values to achieve more concise code (credit: idea by Allen Wirfs-Brock):
Interaction:
This section presents three approaches to enforcing a maximum arity. The running example is a function f
whose maximum arity is 2 – if a caller provides more than 2 parameters, an error should be thrown.
The first approach is to collect all actual parameters in the formal rest parameter args
and to check its length.
The second approach relies on unwanted actual parameters appearing in the formal rest parameter empty
.
The third approach uses a sentinel value that is gone if there is a third parameter. One caveat is that the default value OK
is also triggered if there is a third parameter whose value is undefined
.
Sadly, each one of these approaches introduces significant visual and conceptual clutter. I’m tempted to recommend checking arguments.length
, but I also want arguments
to go away.
...
) The spread operator (...
) looks exactly like the rest operator, but is its opposite:
Math.max()
is a good example for demonstrating how the spread operator works in method calls. Math.max(x1, x2, ···)
returns the argument whose value is greatest. It accepts an arbitrary number of arguments, but can’t be applied to Arrays. The spread operator fixes that:
In contrast to the rest operator, you can use the spread operator anywhere in a sequence of parts:
Another example is JavaScript not having a way to destructively append the elements of one Array to another one. However, Arrays do have the method push(x1, x2, ···)
, which appends all of its arguments to its receiver. The following code shows how you can use push()
to append the elements of arr2
to arr1
.
In addition to function and method calls, the spread operator also works for constructor calls:
That is something that is difficult to achieve in ECMAScript 5.
The spread operator can also be used inside Array literals:
That gives you a convenient way to concatenate Arrays:
One advantage of the spread operator is that its operand can be any iterable value (in contrast to the Array method concat()
, which does not support iteration).
The spread operator lets you convert any iterable value to an Array:
Let’s convert a Set to an Array:
Your own iterable objects can be converted to Arrays in the same manner:
Note that, just like the for-of
loop, the spread operator only works for iterable values. All built-in data structures are iterable: Arrays, Maps and Sets. All Array-like DOM data structures are also iterable.
Should you ever encounter something that is not iterable, but Array-like (indexed elements plus a property length
), you can use Array.from()
6 to convert it to an Array: