4. Spread / Rest Operator

... operator is referred to as spread or rest operator, depending on how and where it is used.

When used with any iterable, it acts as to “spread” it into individual elements:

  1. function foo(x, y, z) {
  2. console.log(x, y, z);
  3. }
  4. let arr = [1, 2, 3];
  5. foo(...arr); // 1 2 3

Spread is also great for shaping a new object from other object(s):

  1. const defaults = {avatar: 'placeholder.jpg', active: false}
  2. const userData = {username: 'foo', avatar: 'bar.jpg'}
  3. console.log({created: '2017-12-31', ...defaults, ...userData})
  4. // {created: "2017-12-31", avatar: "bar.jpg", active: false, username: "foo"}

New arrays can also be shaped expressively:

  1. const arr1 = [1, 2, 3];
  2. const arr2 = [7, 8, 9];
  3. console.log([...arr1, 4, 5, 6, ...arr2]) // [1, 2, 3, 4, 5, 6, 7, 8, 9]

The other common usage of ... is gathering all arguments together into an array. This is referred as “rest” operator.

  1. function foo(...args) {
  2. console.log(args);
  3. }
  4. foo(1, 2, 3, 4, 5); // [1, 2, 3, 4, 5]