ES2018 features - rest / spread object properties

The new rest / spread object operators were added to the language as part of the recent es2018 release. These operators already exist for arrays as rest / spread elements, as they were added as part of ES6 spec a few years back.

They enable composing properties into objects (rest) and expanding out object properties (spread).

More detailed explanations found are as follows: -

Rest properties collect the remaining own enumerable property keys that are not already picked off by the destructuring pattern. Those keys and their values are copied onto a new object.

and

Spread properties in object initializers copies own enumerable properties from a provided object onto the newly created object.

The syntax is simply three dots followed by specific identifier i.e. ...<Binding Identifier>

Here are some basic examples

Rest

  const o  = { a: 1, b: 2, c: 3, d: 4 };
  const { a , b ,  ...x } = o;  // The rest of the properties (c and d)
                                // get composed into x
  console.log(x);               // => { c: 3, d: 4 }

Spread

  const o = { a: 1, b: 2, c: 3 };
  const x = { i: 5, ...o };   // The properties in the object o (a, b and c)
                              // get expanded or spread out into x
  console.log(x)              // => { i: 5, a: 1, b: 2, c: 3}

Usecases

Lets see where these come in handy.

Notables

  • These only iterate over own properties, so prototype properties won’t be accessed.
  • Only enumerable properties are iterated over.
comments powered by Disqus