Object Spread

It's our last day looking into the Spread operator, and today we're going over Object Spread. Once more, here's our definition for Spread:

The Spread operator takes an ellipses symbol ... and combines it with what Brandon Morelli terms a receiver in this Medium post. The receiver can be an array, a function, or an object.

The syntax for an Object Spread is:

let objClone = { ...obj };

In this case, the receiver is the object curly bracket notation.

At its most basic application, Object Spread is an easy way to make a copy of an data object:

const person1 = {
  name: 'Joey',
  age: 31,
  occupation: 'Web Developer',
  hungry: true,
};

const duplicatePerson = { ...person1 };
console.log(duplicatePerson);
// expected result: { name: 'Joey', age: 31, occupation: 'Web Developer', hungry: true }

Similar to Array Spread's ability to add new items into your new receiver array, you can also combine multiple data objects, while also adding new key-value pairs to the receiver data object. Note that if the two objects you are spreading into the receiver have a key of the same name, the second key-value will overwrite the first.

const basicPersonDetails = {
  firstName: 'Joey',
  age: 31,
};

const advancedPersonDetails = {
  firstName: 'Joseph',
  lastName: 'Reyes',
  hungry: true,
};

const person = { ...basicPersonDetails, favoriteColor: 'Blue', ...advancedPersonDetails };
console.log(person);
// expected result: { firstName: 'Joseph', age: 31, favoriteColor: 'Blue', lastName: 'Reyes', hungry: true }

From MDN: Spread syntax allows an iterable such as an array expression or string to be expanded in places where zero or more arguments (for function calls) or elements (for array literals) are expected, or an object expression to be expanded in places where zero or more key-value pairs (for object literals) are expected.

See more examples and documentation here.

More Spread Syntax

Read more about Spread Syntax, Destructuring, and Rest here:

  1. Array Spread
  2. Function Spread
  3. Object Spread
  4. Array Destructuring
  5. Object Destructuring
  6. Rest Syntax