It's not 100% clear to me how this piece of code works:
var a = [1, 2, 3];
[x, y, ...a ] = [0, ...a, 4];
// OUTPUT: [0, 1, 2, 3, 4]
I'm deconstructing the array a
using the ...
operator.
I am expecting that in second line a bunch of assignments will take place.
The x
will be assigned to 0, y
will be assigned to ...a
(which passes the elements in the array a
as individual values).
It's not clear to me, though, how the ...a
get assigned to 4. In fact, JS throws an exception when doing:
...a = 4;
// Uncaught SyntaxError: Rest parameter may not have a default initializer
Why does this code output the modified array with the end 4
, instead of throwing an exception? How does this work exactly?