Why is `...` both spread and rest?
One symbol, two opposite operations: how JavaScript knows whether to gather or scatter.
... gathers arguments into an array; on the next it scatters an array back out. One symbol for two opposite jobs? That's like a post office where the same button both accepts and hands out parcels.There's actually just one rule, and it's about position:
- where variables are created — in function parameters and on the left of
=when destructuring — ... gathers the rest into a new array or object. That's rest; - where values are used — in a function call, inside
[ ]and{ }literals — ... scatters an existing array or object into pieces. That's spread.
In short: on the receiving side it's a sack; on the giving side it's tipping the sack out.
function pack(...items) {
return items;
}
const bag = pack("ball", "fish", "yarn");
console.log(bag);
const [first, ...others] = bag;
console.log(first, others);
console.log(Math.max(...[3, 9, 2]));
console.log([...others, "mouse"]);... create variables — they gather. The last two sit among values — they scatter.Why one symbol? Because these are mirror operations. Look at the pair function send(...args) and send(...list): the call scatters an array into arguments, and the function gathers them back into an array. The same notation on both sides of the call says it plainly: "what I scattered, I gather".
The mirror also explains a restriction: there can be only one sack, and it must come last. const [...middle, last] = arr is a syntax error: the engine can't know how much to put in the sack if there are more slots after it.
A bit of history. Before 2015 there was no rest and no spread. A function taking any number of arguments read them from a special arguments object. It looks like an array — indexes and length — but it isn't one: it has no array methods, and arrow functions don't get their own arguments at all. To pass an array as arguments, people wrote Math.max.apply(null, nums). The ES2015 standard replaced both clumsy constructs with one symbol.
function oldStyle() {
console.log(arguments.length);
console.log(Array.isArray(arguments));
}
oldStyle("Mittens", "Oscar");
function newStyle(...names) {
console.log(names.length);
console.log(Array.isArray(names));
}
newStyle("Mittens", "Oscar");
console.log(Math.max.apply(null, [3, 9, 2]));
console.log(Math.max(...[3, 9, 2]));arguments is an "almost array". A rest parameter is a real one. The old and new ways to spread an array into arguments.const order = { id: 1, address: { city: "London" } };
const copy = { ...order };
copy.address.city = "Leeds";
console.log(order.address.city);
const moved = { ...order, address: { ...order.address, city: "York" } };
console.log(order.address.city, moved.address.city);address with the original. The second copied address too — the original is safe.Myth or fact?
Decide whether the statement is true. Got it wrong? Try again; once you're right, Byte explains what's going on.