ES6 Spread Operator and Rest Parameter


Published: 2017-11-19
Updated: 2017-12-26
Web: http://fritzthecat-blog.blogspot.com/2017/11/es6-spread-operator-and-rest-parameter.html


The ES6 spread-operator is more than C's varargs (→ variadic arguments) or Java's ellipsis. Besides expressing uncertain parameters it also can be used to create or destructure arrays.

Here is an example of a C function prototype with varargs, like written in a header.h file:

int printf(char* format, ...);

The same in Java, like written in an interface:

int printf(String format, Object ... arguments);

It got from being a "..." in C to being a typed and named "...".

In ES6 it's going to be untyped, but named.

function printf(format, ... parameterArray) {
    // Spaces can be between spread-operator and parameter-name,
    // but it's better understandable without!
}

This is called Rest Parameter. It must be the last parameter, nothing behind it.

The "..." part is called Spread Operator, and it uses iteration to destructure whatever is right of it. Thus the right-of-it must implement iterable. An Array, a Map, a String, they all do it. An Object does not.

const characters = [ ..."abc" ]

This creates an array-clone from the character-array of a string (see example below).

ES6: ?

ES6 Spread Operator Tests


Description

Resume

With ES6, you can destructure an array const oneTwoArray = [ "One", "Two" ] to function-parameters

Expressing the same thing in different ways? Hm ...

All elements of array firstArray are inserted at second position into the array firstArray. Mind that the value 100 gets shifted two positions backwards by that operation!

We have an array called parameters that we want to pass as an argument list to a function, so that the first array element is the first paramter, the second element the second parameter, and so on. Thus we put the parameters array into the call of the function, and prepend the spread-operator to destructure it.

This is called rest parameter.

The function receiveParametersAsArray receives every argument after the first one as an array named parameterArray. This resembles the classical varargs. Mind that this technique makes it absolutely necessary to document the function parameters, else no one will be abe to use this function without reading its source code, and the source code of all functions that it calls. Try to avoid the rest-parameter!

The spread-operator uses the iterable protocols, and thus can spread all objects that implement these conventions, in this case it spreads the characters of a String-object.





ɔ⃝ Fritz Ritzberger, 2017-11-19