ES6 Spread Operator


This post goes over how ES6 spread operator works.

Object

Use spread to make a shallow copy of an object:

const object = {
  key: 'value',
};

const copy = {
  ...object,
};

assert.deepEqual(object, copy);
assert.notStrictEqual(object, copy);

Object.assign() is an alternative to object spread syntax:

const object = {
  key: 'value',
};

const copy = Object.assign({}, object);

assert.deepEqual(object, copy);

If the value is not an object or array, spread will do nothing:

assert.deepEqual({}, { ...undefined });
assert.deepEqual({}, { ...null });
assert.deepEqual({}, { ...false });
assert.deepEqual({}, { ...0 });

Spread can be used to merge objects:

const john = {
  name: 'John',
  age: 42,
};

const mary = {
  name: 'Mary',
};

const merge = {
  ...john,
  ...mary,
};

assert.deepEqual(merge, { name: 'Mary', age: 42 });

Note that the order matters:

const merge = {
  ...mary,
  ...john,
};

assert.deepEqual(merge, { name: 'John', age: 42 });

Array

Use spread to make a shallow copy of an array:

const array = [0, 1, 2];
const copy = [...array];

assert.deepEqual(array, copy);
assert.notStrictEqual(array, copy);

Array.slice is an alternative to array spread syntax:

const array = [0, 1, 2];
const copy = array.slice();

assert.deepEqual(array, copy);

If the value is not an iterable, spread will throw an error:

// Uncaught TypeError: undefined is not iterable
assert.throws(() => [...undefined]);

Spread can be used to merge arrays:

const animals = ['cat', 'dog'];
const fruits = ['apple', 'banana'];
const merge = [...animals, ...fruits];

assert.deepEqual(merge, ['cat', 'dog', 'apple', 'banana']);

Note that the order matters:

const animals = ['cat', 'dog'];
const fruits = ['apple', 'banana'];
const merge = [...fruits, ...animals];

assert.deepEqual(merge, ['apple', 'banana', 'cat', 'dog']);

Function

Spread function arguments:

function fun(...args) {
  assert(Array.isArray(args));
}

Spread can be a replacement for arguments:

function fun(...args) {
  assert.deepEqual(args, [...arguments]);
}


Please support this site and join our Discord!