Please support this book: buy it or donate

6. Rest/Spread Properties



The ECMAScript proposal “Rest/Spread Properties” by Sebastian Markbåge enables:

  • The rest operator () in object destructuring. At the moment, this operator only works for Array destructuring and in parameter definitions.

  • The spread operator () in object literals. At the moment, this operator only works in Array literals and in function and method calls.

6.1. The rest operator (…) in object destructuring

Inside object destructuring patterns, the rest operator () copies all enumerable own properties of the destructuring source into its operand, except those that were already mentioned in the object literal.

  1. const obj = {foo: 1, bar: 2, baz: 3};
  2. const {foo, ...rest} = obj;
  3. // Same as:
  4. // const foo = 1;
  5. // const rest = {bar: 2, baz: 3};

If you are using object destructuring to handle named parameters, the rest operator enables you to collect all remaining parameters:

  1. function func({param1, param2, ...rest}) { // rest operator
  2. console.log('All parameters: ',
  3. {param1, param2, ...rest}); // spread operator
  4. return param1 + param2;
  5. }

6.1.1. Syntactic restrictions

Per top level of each object literal, you can use the rest operator at most once and it must appear at the end:

  1. const {...rest, foo} = obj; // SyntaxError
  2. const {foo, ...rest1, ...rest2} = obj; // SyntaxError

You can, however, use the rest operator several times if you nest it:

  1. const obj = {
  2. foo: {
  3. a: 1,
  4. b: 2,
  5. c: 3,
  6. },
  7. bar: 4,
  8. baz: 5,
  9. };
  10. const {foo: {a, ...rest1}, ...rest2} = obj;
  11. // Same as:
  12. // const a = 1;
  13. // const rest1 = {b: 2, c: 3};
  14. // const rest2 = {bar: 4, baz: 5};

6.2. The spread operator (…) in object literals

Inside object literals, the spread operator () inserts all enumerable own properties of its operand into the object created via the literal:

  1. > const obj = {foo: 1, bar: 2};
  2. > {...obj, baz: 3}
  3. { foo: 1, bar: 2, baz: 3 }

Note that order matters even if property keys don’t clash, because objects record insertion order:

  1. > {baz: 3, ...obj}
  2. { baz: 3, foo: 1, bar: 2 }

If keys clash, order determines which entry “wins”:

  1. > const obj = {foo: 1, bar: 2, baz: 3};
  2. > {...obj, foo: true}
  3. { foo: true, bar: 2, baz: 3 }
  4. > {foo: true, ...obj}
  5. { foo: 1, bar: 2, baz: 3 }

6.3. Common use cases for the object spread operator

In this section, we’ll look at things that you can use the spread operator for. I’ll also show how to do these things via Object.assign(), which is very similar to the spread operator (we’ll compare them in more detail later).

6.3.1. Cloning objects

Cloning the enumerable own properties of an object obj:

  1. const clone1 = {...obj};
  2. const clone2 = Object.assign({}, obj);

The prototypes of the clones are always Object.prototype, which is the default for objects created via object literals:

  1. > Object.getPrototypeOf(clone1) === Object.prototype
  2. true
  3. > Object.getPrototypeOf(clone2) === Object.prototype
  4. true
  5. > Object.getPrototypeOf({}) === Object.prototype
  6. true

Cloning an object obj, including its prototype:

  1. const clone1 = {__proto__: Object.getPrototypeOf(obj), ...obj};
  2. const clone2 = Object.assign(
  3. Object.create(Object.getPrototypeOf(obj)), obj);

Note that proto inside object literals is only a mandatory feature in web browsers, not in JavaScript engines in general.

6.3.2. True clones of objects

Sometimes you need to faithfully copy all own properties of an object obj and their attributes (writable, enumerable, …), including getters and setters. Then Object.assign() and the spread operator don’t work. You need to use property descriptors:

  1. const clone1 = Object.defineProperties({},
  2. Object.getOwnPropertyDescriptors(obj));

If you additionally want to preserve the prototype of obj, you can use Object.create():

  1. const clone2 = Object.create(
  2. Object.getPrototypeOf(obj),
  3. Object.getOwnPropertyDescriptors(obj));

Object.getOwnPropertyDescriptors() is explained in “Exploring ES2016 and ES2017”.

6.3.3. Pitfall: cloning is always shallow

Keep in mind that with all the ways of cloning that we have looked at, you only get shallow copies: If one of the original property values is an object, the clone will refer to the same object, it will not be (recursively, deeply) cloned itself:

  1. const original = { prop: {} };
  2. const clone = Object.assign({}, original);
  3. console.log(original.prop === clone.prop); // true
  4. original.prop.foo = 'abc';
  5. console.log(clone.prop.foo); // abc

6.3.4. Various other use cases

Merging two objects obj1 and obj2:

  1. const merged = {...obj1, ...obj2};
  2. const merged = Object.assign({}, obj1, obj2);

Filling in defaults for user data:

  1. const DEFAULTS = {foo: 'a', bar: 'b'};
  2. const userData = {foo: 1};
  3. const data = {...DEFAULTS, ...userData};
  4. const data = Object.assign({}, DEFAULTS, userData);
  5. // {foo: 1, bar: 'b'}

Specifying the default values for properties foo and bar inline:

  1. const userData = {foo: 1};
  2. const data = {foo: 'a', bar: 'b', ...userData};
  3. const data = Object.assign({}, {foo:'a', bar:'b'}, userData);
  4. // {foo: 1, bar: 'b'}

Non-destructively updating property foo:

  1. const obj = {foo: 'a', bar: 'b'};
  2. const obj2 = {...obj, foo: 1};
  3. const obj2 = Object.assign({}, obj, {foo: 1});
  4. // {foo: 1, bar: 'b'}

6.4. Spreading objects versus Object.assign()

The spread operator and Object.assign() are very similar. The main difference is that spreading defines new properties, while Object.assign() sets them. What exactly that means is explained later.

6.4.1. The two ways of using Object.assign()

There are two ways of using Object.assign():

First, destructively (an existing object is changed):

  1. Object.assign(target, source1, source2);

Here, target is modified; source1 and source2 are copied into it.

Second, non-destructively (no existing object is changed):

  1. const result = Object.assign({}, source1, source2);

Here, a new object is created via an empty object literal and source1 and source2 are copied into it. At the end, this new object is returned and assigned to result.

The spread operator is very similar to the second way of using Object.assign(). Next, we’ll look at where the two are similar and where they differ.

6.4.2. Both spread and Object.assign() read values via a “get” operation

Both operations use normal “get” operations to read property values from the source, before writing them to the target. As a result, getters are turned into normal data properties during this process.

Let’s look at an example:

  1. const original = {
  2. get foo() {
  3. return 123;
  4. }
  5. };

original has the getter foo (its property descriptor has the properties get and set):

  1. > Object.getOwnPropertyDescriptor(original, 'foo')
  2. { get: [Function: foo],
  3. set: undefined,
  4. enumerable: true,
  5. configurable: true }

But it its clones clone1 and clone2, foo is a normal data property (its property descriptor has the properties value and writable):

  1. > const clone1 = {...original};
  2. > Object.getOwnPropertyDescriptor(clone1, 'foo')
  3. { value: 123,
  4. writable: true,
  5. enumerable: true,
  6. configurable: true }
  7. > const clone2 = Object.assign({}, original);
  8. > Object.getOwnPropertyDescriptor(clone2, 'foo')
  9. { value: 123,
  10. writable: true,
  11. enumerable: true,
  12. configurable: true }

6.4.3. Spread defines properties, Object.assign() sets them

The spread operator defines new properties in the target, Object.assign() uses a normal “set” operation to create them. That has two consequences.

6.4.3.1. Targets with setters

First, Object.assign() triggers setters, spread doesn’t:

  1. Object.defineProperty(Object.prototype, 'foo', {
  2. set(value) {
  3. console.log('SET', value);
  4. },
  5. });
  6. const obj = {foo: 123};

The previous piece of code installs a setter foo that is inherited by all normal objects.

If we clone obj via Object.assign(), the inherited setter is triggered:

  1. > Object.assign({}, obj)
  2. SET 123
  3. {}

With spread, it isn’t:

  1. > { ...obj }
  2. { foo: 123 }

Object.assign() also triggers own setters during copying, it does not overwrite them.

6.4.3.2. Targets with read-only properties

Second, you can stop Object.assign() from creating own properties via inherited read-only properties, but not the spread operator:

  1. Object.defineProperty(Object.prototype, 'bar', {
  2. writable: false,
  3. value: 'abc',
  4. });

The previous piece of code installs the read-only property bar that is inherited by all normal objects.

As a consequence, you can’t use assignment to create the own property bar, anymore (you only get an exception in strict mode; in sloppy mode, setting fails silently):

  1. > const tmp = {};
  2. > tmp.bar = 123;
  3. TypeError: Cannot assign to read only property 'bar'

In the following code, we successfully create the property bar via an object literal. This works, because object literals don’t set properties, they define them:

  1. const obj = {bar: 123};

However, Object.assign() uses assignment for creating properties, which is why we can’t clone obj:

  1. > Object.assign({}, obj)
  2. TypeError: Cannot assign to read only property 'bar'

Cloning via the spread operator works:

  1. > { ...obj }
  2. { bar: 123 }

6.4.4. Both spread and Object.assign() only consider own enumerable properties

Both operations ignore all inherited properties and all non-enumerable own properties.

The following object obj inherits one (enumerable!) property from proto and has two own properties:

  1. const proto = {
  2. inheritedEnumerable: 1,
  3. };
  4. const obj = Object.create(proto, {
  5. ownEnumerable: {
  6. value: 2,
  7. enumerable: true,
  8. },
  9. ownNonEnumerable: {
  10. value: 3,
  11. enumerable: false,
  12. },
  13. });

If you clone obj, the result only has the property ownEnumerable. The properties inheritedEnumerable and ownNonEnumerable are not copied:

  1. > {...obj}
  2. { ownEnumerable: 2 }
  3. > Object.assign({}, obj)
  4. { ownEnumerable: 2 }