Spead assignment operator

Since its introduction in ES6, the spead operator (...) has found many uses.

I often find myself extending an object or array like this:

a = {
    ...a,
    ...b,
};

What about adding an assignment operator (like a += 3) but for the spead operator:

a ...= b;

// or

a ...= {
    foo: 'bar',
};

The issue with the proposed a ...= b syntax, is that the ... operator has different meanings depending on context, and that context is lacking in ...=. More specifically:

a = [ ...a, ...b ];

Here, a and b are considered as iterables (as are arrays, sets, maps, generators), and the ... operator iterates over the corresponding values or entries.

a = { ...a, ...b };

Here, a and b are considered as objects, and the ... operator iterates over the corresponding properties

a ...= b

Should b be treated as iterable or as object—knowing that a value is often both? A careful introspection on a and/or b may help to guess the intent, but the guess may be wrong.


BTW, instead of the proposed a ...= b, you can already write as of today: Object.assign(a, b).
.

1 Like