11. Object rest/spread

Object rest

Rest properties allows to collect the properties from an object that are left after a destructuring assignment.

const object = {
  propA: 1,
  propB: 2,
  propC: 3
};

const { propA, ...restObject } = object;
propA; // => 1
restObject; // => { propB: 2, propC: 3 }
  • use the rest operator at most once;

  • rest operator must appear at the end;

  • you can use the rest operator several times if you nest it.

Object spread

Spread properties allows to copy into an object literal the owned properties from a source object. In this example the object literal collects into object additional properties from source object:

const source = {
  propB: 2,
  propC: 3
};
const object = {
  propA: 1,
  ...source
};
object; // => { propA: 1, propB: 2, propC: 3 }

It copies own enumerable properties from a provided object onto a new object. Shallow-cloning (excluding prototype) or merging objects is now possible using a shorter syntax than Object.assign().

Rest/Spread операторы никогда не меняют исходный объект.

Last updated

Was this helpful?