5.2 Array literals

5.2.1 Use trailing commas

Include a trailing comma whenever there is a line break between the finalelement and the closing bracket.

Example:

  1. const values = [
  2. 'first value',
  3. 'second value',
  4. ];

5.2.2 Do not use the variadic Array constructor

The constructor is error-prone if arguments are added or removed. Use a literalinstead.

Disallowed:

  1. const a1 = new Array(x1, x2, x3);
  2. const a2 = new Array(x1, x2);
  3. const a3 = new Array(x1);
  4. const a4 = new Array();

This works as expected except for the third case: if x1 is a whole number thena3 is an array of size x1 where all elements are undefined. If x1 is anyother number, then an exception will be thrown, and if it is anything else thenit will be a single-element array.

Instead, write

  1. const a1 = [x1, x2, x3];
  2. const a2 = [x1, x2];
  3. const a3 = [x1];
  4. const a4 = [];

Explicitly allocating an array of a given length using new Array(length) isallowed when appropriate.

5.2.3 Non-numeric properties

Do not define or use non-numeric properties on an array (other thanlength). Use a Map (or Object) instead.

5.2.4 Destructuring

Array literals may be used on the left-hand side of an assignment to performdestructuring (such as when unpacking multiple values from a single array oriterable). A final rest element may be included (with no space between the and the variable name). Elements should be omitted if they are unused.

  1. const [a, b, c, ...rest] = generateResults();
  2. let [, b,, d] = someArray;

Destructuring may also be used for function parameters (note that a parametername is required but ignored). Always specify [] as the default value if adestructured array parameter is optional, and provide default values on the lefthand side:

  1. /** @param {!Array<number>=} param1 */
  2. function optionalDestructuring([a = 4, b = 2] = []) { };

Disallowed:

  1. function badDestructuring([a, b] = [4, 2]) { };

Tip: For (un)packing multiple values into a function’s parameter or return,prefer object destructuring to array destructuring when possible, as it allowsnaming the individual elements and specifying a different type for each.

5.2.5 Spread operator

Array literals may include the spread operator () to flatten elements outof one or more other iterables. The spread operator should be used instead ofmore awkward constructs with Array.prototype. There is no space after the.

Example:

  1. [...foo] // preferred over Array.prototype.slice.call(foo)
  2. [...foo, ...bar] // preferred over foo.concat(bar)