In the below code,
function myFunction(x, y, z) { }
var args = [0, 1, 2];
myFunction(...args);
Is spread operator(...
) unpacking the array and providing 3 values 0, 1, 2?
In the below code,
function myFunction(x, y, z) { }
var args = [0, 1, 2];
myFunction(...args);
Is spread operator(...
) unpacking the array and providing 3 values 0, 1, 2?
Yes, as per the page that contains the example you posted:
Running the following through an ES6 transpiler:
produces:
which logs
0 1 2
, showing it has expanded theargs
array....
is known as Spread/Rest operator depending upon how and where it is used.What does spread operator do? The spread operator allows an expression to be expanded in places where multiple elements/variables/arguments are expected.
Before ES6, arguments is an array like object, corresponds to the arguments passed to a function. Here is a quick look at its use:
In ES6, the same can be written as:
can call either of two ways:
or
We have put
...
in front of array, so it spread the elements of array into individual values.Yes, that's exactly what the spread operator does.
It is the equivalent of replacing the identifier containing the iterable with an comma seperated list of values that are the output of iterating the iterable.
In your case, the iterable is an array, and the equivalent is
0, 1, 2
.Had the iterable been the output of a generator function it would be the same:
A powerful use of the operator is when values are not "static" like this: