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().

const obj1 = { foo: "bar", x: 42 };
const obj2 = { foo: "baz", y: 13 };

// Cloning the enumerable own properties of an object obj:
const clonedObj = { ...obj1 };
// Object { foo: "bar", x: 42 }

// Merging two objects obj1 and obj2:
const mergedObj = { ...obj1, ...obj2 };
// Object { foo: "baz", x: 42, y: 13 }

// Filling in defaults for user data:
const data = { ...DEFAULTS, ...userData };

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

Last updated