Please support this book: buy it (PDF, EPUB, MOBI) or donate

11. Parameter handling

11.1 Overview

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.

11.1.1 Default parameter values

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:

  1. function func(x, y=0) {
  2. return [x, y];
  3. }
  4. func(1, 2); // [1, 2]
  5. func(1); // [1, 0]
  6. func(); // [undefined, 0]

11.1.2 Rest parameters

If you prefix a parameter name with the rest operator (), that parameter receives all remaining parameters via an Array:

  1. function format(pattern, ...params) {
  2. return {pattern, params};
  3. }
  4. format(1, 2, 3);
  5. // { pattern: 1, params: [ 2, 3 ] }
  6. format();
  7. // { pattern: undefined, params: [] }

11.1.3 Named parameters via destructuring

You can simulate named parameters if you destructure with an object pattern in the parameter list:

  1. function selectEntries({ start=0, end=-1, step=1 } = {}) { // (A)
  2. // The object pattern is an abbreviation of:
  3. // { start: start=0, end: end=-1, step: step=1 }
  4.  
  5. // Use the variables `start`, `end` and `step` here
  6. ···
  7. }
  8.  
  9. selectEntries({ start: 10, end: 30, step: 2 });
  10. selectEntries({ step: 3 });
  11. selectEntries({});
  12. selectEntries();

The = {} in line A enables you to call selectEntries() without paramters.

11.1.4 Spread operator (…)

In function and constructor calls, the spread operator turns iterable values into arguments:

  1. > Math.max(-1, 5, 11, 3)
  2. 11
  3. > Math.max(...[-1, 5, 11, 3])
  4. 11
  5. > Math.max(-1, ...[-5, 11], 3)
  6. 11

In Array literals, the spread operator turns iterable values into Array elements:

  1. > [1, ...[2,3], 4]
  2. [1, 2, 3, 4]

11.2 Parameter handling as destructuring

The ES6 way of handling parameters is equivalent to destructuring the actual parameters via the formal parameters. That is, the following function call:

  1. function func(«FORMAL_PARAMETERS») {
  2. «CODE»
  3. }
  4. func(«ACTUAL_PARAMETERS»);

is roughly equivalent to:

  1. {
  2. let [«FORMAL_PARAMETERS»] = [«ACTUAL_PARAMETERS»];
  3. {
  4. «CODE»
  5. }
  6. }

Example – the following function call:

  1. function logSum(x=0, y=0) {
  2. console.log(x + y);
  3. }
  4. logSum(7, 8);

becomes:

  1. {
  2. let [x=0, y=0] = [7, 8];
  3. {
  4. console.log(x + y);
  5. }
  6. }

Let’s look at specific features next.

11.3 Parameter default values

ECMAScript 6 lets you specify default values for parameters:

  1. function f(x, y=0) {
  2. return [x, y];
  3. }

Omitting the second parameter triggers the default value:

  1. > f(1)
  2. [1, 0]
  3. > f()
  4. [undefined, 0]

Watch out – undefined triggers the default value, too:

  1. > f(undefined, undefined)
  2. [undefined, 0]

The default value is computed on demand, only when it is actually needed:

  1. > const log = console.log.bind(console);
  2. > function g(x=log('x'), y=log('y')) {return 'DONE'}
  3. > g()
  4. x
  5. y
  6. 'DONE'
  7. > g(1)
  8. y
  9. 'DONE'
  10. > g(1, 2)
  11. 'DONE'

11.3.1 Why does 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().

  1. function setLevel(newLevel = 0) {
  2. light.intensity = newLevel;
  3. }
  4. function setOptions(options) {
  5. // Missing prop returns undefined => use default
  6. setLevel(options.dimmerLevel);
  7. setMotorSpeed(options.speed);
  8. ···
  9. }
  10. setOptions({speed:5});

In the second example, square() doesn’t have to define a default for x, it can delegate that task to multiply():

  1. function multiply(x=1, y=1) {
  2. return x * y;
  3. }
  4. function square(x) {
  5. return multiply(x, x);
  6. }

Default values further entrench the role of undefined as indicating that something doesn’t exist, versus null indicating emptiness.

11.3.2 Referring to other parameters in default values

Within a parameter default value, you can refer to any variable, including other parameters:

  1. function foo(x=3, y=x) {}
  2. foo(); // x=3; y=3
  3. foo(7); // x=7; y=7
  4. foo(7, 2); // x=7; y=2

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:

  1. function bar(x=y, y=4) {}
  2. bar(3); // OK
  3. bar(); // ReferenceError: y is not defined

11.3.3 Referring to “inner” variables in default values

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:

  1. const x = 'outer';
  2. function foo(a = x) {
  3. const x = 'inner';
  4. console.log(a); // outer
  5. }

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:

  1. const QUX = 2;
  2. function bar(callback = () => QUX) { // returns 2
  3. const QUX = 3;
  4. callback();
  5. }
  6. bar(); // ReferenceError

11.4 Rest parameters

Putting the rest operator () in front of the last formal parameter means that it will receive all remaining actual parameters in an Array.

  1. function f(x, ...y) {
  2. ···
  3. }
  4. f('a', 'b', 'c'); // x = 'a'; y = ['b', 'c']

If there are no remaining parameters, the rest parameter will be set to the empty Array:

  1. f(); // x = undefined; y = []

11.4.1 No more arguments!

Rest parameters can completely replace JavaScript’s infamous special variable arguments. They have the advantage of always being Arrays:

  1. // ECMAScript 5: arguments
  2. function logAllArguments() {
  3. for (var i=0; i < arguments.length; i++) {
  4. console.log(arguments[i]);
  5. }
  6. }
  7.  
  8. // ECMAScript 6: rest parameter
  9. function logAllArguments(...args) {
  10. for (const arg of args) {
  11. console.log(arg);
  12. }
  13. }
11.4.1.1 Combining destructuring and access to the destructured value

One interesting feature of arguments is that you can have normal parameters and an Array of all parameters at the same time:

  1. function foo(x=0, y=0) {
  2. console.log('Arity: '+arguments.length);
  3. ···
  4. }

You can avoid arguments in such cases if you combine a rest parameter with Array destructuring. The resulting code is longer, but more explicit:

  1. function foo(...args) {
  2. let [x=0, y=0] = args;
  3. console.log('Arity: '+args.length);
  4. ···
  5. }

The same technique works for named parameters (options objects):

  1. function bar(options = {}) {
  2. let { namedParam1, namedParam2 } = options;
  3. ···
  4. if ('extra' in options) {
  5. ···
  6. }
  7. }
11.4.1.2 arguments is iterable

arguments is iterable5 in ECMAScript 6, which means that you can use for-of and the spread operator:

  1. > (function () { return typeof arguments[Symbol.iterator] }())
  2. 'function'
  3. > (function () { return Array.isArray([...arguments]) }())
  4. true

11.5 Simulating named parameters

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:

  • Positional parameters are mapped by position. The first actual parameter is mapped to the first formal parameter, the second actual to the second formal, and so on:
  1. selectEntries(3, 20, 2)
  • Named parameters use names (labels) to perform the mapping. Formal parameters have labels. In a function call, these labels determine which value belongs to which formal parameter. It does not matter in which order named actual parameters appear, as long as they are labeled correctly. Simulating named parameters in JavaScript looks as follows.
  1. selectEntries({ start: 3, end: 20, step: 2 })

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.

11.5.1 Named Parameters as Descriptions

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:

  1. selectEntries(3, 20, 2);

what do these three numbers mean? Python supports named parameters, and they make it easy to figure out what is going on:

  1. # Python syntax
  2. selectEntries(start=3, end=20, step=2)

11.5.2 Optional Named Parameters

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:

  1. # Python syntax
  2. selectEntries(step=2)
  3. selectEntries(end=20, start=3)
  4. selectEntries()

11.5.3 Simulating Named Parameters in JavaScript

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.

  1. selectEntries({ start: 3, end: 20, step: 2 });

The function receives an object with the properties start, end, and step. You can omit any of them:

  1. selectEntries({ step: 2 });
  2. selectEntries({ end: 20, start: 3 });
  3. selectEntries();

In ECMAScript 5, you’d implement selectEntries() as follows:

  1. function selectEntries(options) {
  2. options = options || {};
  3. var start = options.start || 0;
  4. var end = options.end || -1;
  5. var step = options.step || 1;
  6. ···
  7. }

In ECMAScript 6, you can use destructuring, which looks like this:

  1. function selectEntries({ start=0, end=-1, step=1 }) {
  2. ···
  3. }

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.

  1. function selectEntries({ start=0, end=-1, step=1 } = {}) {
  2. ···
  3. }

You can also combine positional parameters with named parameters. It is customary for the latter to come last:

  1. someFunc(posArg1, { namedArg1: 7, namedArg2: true });

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.

11.6 Examples of destructuring in parameter handling

11.6.1 forEach() and destructuring

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.

  1. const items = [ ['foo', 3], ['bar', 9] ];
  2. items.forEach(([word, count]) => {
  3. console.log(word+' '+count);
  4. });

Second example: destructuring the objects in an Array.

  1. const items = [
  2. { word:'foo', count:3 },
  3. { word:'bar', count:9 },
  4. ];
  5. items.forEach(({word, count}) => {
  6. console.log(word+' '+count);
  7. });

11.6.2 Transforming Maps

An ECMAScript 6 Map doesn’t have a method map() (like Arrays). Therefore, one has to:

  • Step 1: Convert it to an Array of [key,value] pairs.
  • Step 2: map() the Array.
  • Step 3: Convert the result back to a Map. This looks as follows.
  1. const map0 = new Map([
  2. [1, 'a'],
  3. [2, 'b'],
  4. [3, 'c'],
  5. ]);
  6.  
  7. const map1 = new Map( // step 3
  8. [...map0] // step 1
  9. .map(([k, v]) => [k*2, '_'+v]) // step 2
  10. );
  11. // Resulting Map: {2 -> '_a', 4 -> '_b', 6 -> '_c'}

11.6.3 Handling an Array returned via a Promise

The tool method Promise.all() works as follows:

  • Input: an iterable of Promises.
  • Output: a Promise that is fulfilled with an Array as soon as the last input Promise is fulfilled. That Array contains the fulfillments of the input Promises. Destructuring helps with handling the Array that the result of Promise.all() is fulfilled with:
  1. const urls = [
  2. 'http://example.com/foo.html',
  3. 'http://example.com/bar.html',
  4. 'http://example.com/baz.html',
  5. ];
  6.  
  7. Promise.all(urls.map(downloadUrl))
  8. .then(([fooStr, barStr, bazStr]) => {
  9. ···
  10. });
  11.  
  12. // This function returns a Promise that is fulfilled
  13. // with a string (the text)
  14. function downloadUrl(url) {
  15. return fetch(url).then(request => request.text());
  16. }

fetch() is a Promise-based version of XMLHttpRequest. It is part of the Fetch standard.

11.7 Coding style tips

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.

11.7.1 Optional parameters

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.

  1. function foo(requiredParam, optionalParam = undefined) {
  2. ···
  3. }

11.7.2 Required parameters

In ECMAScript 5, you have a few options for ensuring that a required parameter has been provided, which are all quite clumsy:

  1. function foo(mustBeProvided) {
  2. if (arguments.length < 1) {
  3. throw new Error();
  4. }
  5. if (! (0 in arguments)) {
  6. throw new Error();
  7. }
  8. if (mustBeProvided === undefined) {
  9. throw new Error();
  10. }
  11. ···
  12. }

In ECMAScript 6, you can (ab)use default parameter values to achieve more concise code (credit: idea by Allen Wirfs-Brock):

  1. /**
  2. * Called if a parameter is missing and
  3. * the default value is evaluated.
  4. */
  5. function mandatory() {
  6. throw new Error('Missing parameter');
  7. }
  8. function foo(mustBeProvided = mandatory()) {
  9. return mustBeProvided;
  10. }

Interaction:

  1. > foo()
  2. Error: Missing parameter
  3. > foo(123)
  4. 123

11.7.3 Enforcing a maximum arity

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.

  1. function f(...args) {
  2. if (args.length > 2) {
  3. throw new Error();
  4. }
  5. // Extract the real parameters
  6. let [x, y] = args;
  7. }

The second approach relies on unwanted actual parameters appearing in the formal rest parameter empty.

  1. function f(x, y, ...empty) {
  2. if (empty.length > 0) {
  3. throw new Error();
  4. }
  5. }

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.

  1. const OK = Symbol();
  2. function f(x, y, arity=OK) {
  3. if (arity !== OK) {
  4. throw new Error();
  5. }
  6. }

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.

  1. function f(x, y) {
  2. if (arguments.length > 2) {
  3. throw new Error();
  4. }
  5. }

11.8 The spread operator (…)

The spread operator () looks exactly like the rest operator, but is its opposite:

  • Rest operator: collects the remaining items of an iterable into an Array and is used for rest parameters and destructuring.
  • Spread operator: turns the items of an iterable into arguments of a function call or into elements of an Array.

11.8.1 Spreading into function and method calls

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:

  1. > Math.max(-1, 5, 11, 3)
  2. 11
  3. > Math.max(...[-1, 5, 11, 3])
  4. 11

In contrast to the rest operator, you can use the spread operator anywhere in a sequence of parts:

  1. > Math.max(-1, ...[5, 11], 3)
  2. 11

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.

  1. const arr1 = ['a', 'b'];
  2. const arr2 = ['c', 'd'];
  3.  
  4. arr1.push(...arr2);
  5. // arr1 is now ['a', 'b', 'c', 'd']

11.8.2 Spreading into constructors

In addition to function and method calls, the spread operator also works for constructor calls:

  1. new Date(...[1912, 11, 24]) // Christmas Eve 1912

That is something that is difficult to achieve in ECMAScript 5.

11.8.3 Spreading into Arrays

The spread operator can also be used inside Array literals:

  1. > [1, ...[2,3], 4]
  2. [1, 2, 3, 4]

That gives you a convenient way to concatenate Arrays:

  1. const x = ['a', 'b'];
  2. const y = ['c'];
  3. const z = ['d', 'e'];
  4.  
  5. const arr = [...x, ...y, ...z]; // ['a', 'b', 'c', 'd', 'e']

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).

11.8.3.1 Converting iterable or Array-like objects to Arrays

The spread operator lets you convert any iterable value to an Array:

  1. const arr = [...someIterableObject];

Let’s convert a Set to an Array:

  1. const set = new Set([11, -1, 6]);
  2. const arr = [...set]; // [11, -1, 6]

Your own iterable objects can be converted to Arrays in the same manner:

  1. const obj = {
  2. * [Symbol.iterator]() {
  3. yield 'a';
  4. yield 'b';
  5. yield 'c';
  6. }
  7. };
  8. const arr = [...obj]; // ['a', 'b', 'c']

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:

  1. const arrayLike = {
  2. '0': 'a',
  3. '1': 'b',
  4. '2': 'c',
  5. length: 3
  6. };
  7.  
  8. // ECMAScript 5:
  9. var arr1 = [].slice.call(arrayLike); // ['a', 'b', 'c']
  10.  
  11. // ECMAScript 6:
  12. const arr2 = Array.from(arrayLike); // ['a', 'b', 'c']
  13.  
  14. // TypeError: Cannot spread non-iterable value
  15. const arr3 = [...arrayLike];