The example you've found is a bit contrived, and you probably wouldn't see it in real code. It's just meant to illustrate that the spread argument syntax ...
works with any iterable expression, including standard array literals like [1, 2, 3]
. z
will be 3
because
myFunction(-1, ...args, 2, ...[3]);
is equivalent to
myFunction(-1, ...args, 2, 3);
The ...[
and ]
essentially have no effect in this case; the values are pulled out of the array so it's as though you'd just written them directly in the argument list. As another example,
myFunction(-1, ...args, 2, ...[3, 4, 5]);
is equivalent to
myFunction(-1, ...args, 2, 3, 4, 5);
although z
would still be 3
(4
and 5
would be ignored because they're unexpected extra arguments).
Let's break this down a bit: the behaviour of the spread/rest syntax ...
in an argument list is defined in section 12.3.6.1 "Runtime Semantics: ArgumentListEvaluation" of ECMAScript 6. To paraphrase, it essentially says "when you see ...X
in an argument list, evaluate X
, then go through the values it contains and add each of them as a separate argument".
So, when JavaScript sees , 3
in an argument list, it says "add 3
to the argument list".
But when JavaScript sees , ...[3]
in an argument list, it says "create a new array containing 3
, then go through each of its values (only 3
) and add them to the argument list".
You're doing the same thing in both cases, but the simpler way is probably faster.