ES6 - Spread Operator - Object

ES6 JavaScript

In the previous tutorial we learned about spread operator and how to spread arrays. In this tutorial we will learn to spread objects. So, let's get started.

Spreading objects

We can also spread objects into new object using the spread operator. In the following example we are spreading two objects into a third.

const obj1 = { a: 1, b: 2 };
const obj2 = { c: 3, d: 4 };
const result = { ...obj1, ...obj2 };
console.log(result); // { a: 1, b: 2, c: 3, d: 4 }

So, in the above code we are first spreading the properties of object obj1 into result.

result = { a: 1, b: 2 }

Then we are spreading the properties of object obj2 into the result.

result = { a: 1, b: 2, c: 3, d: 4 }

Note! If an object is spreading with a different value of a given property then new value overwrites the old.

In the following example value of property a: 1 is overwritten to a: 3.

const obj1 = { a: 1, b: 2 };
const obj2 = { c: 3, d: 4, a: 3 };
const result = { ...obj1, ...obj2 };
console.log(result); // { a: 3, b: 2, c: 3, d: 4 }

So, when we spread object obj1 the result becomes the following.

result = { a: 3, b: 2 }

And when we spread object obj2 the value of property a: 1 in result is overwritten by the new value from obj2 a: 3. So, result becomes the following.

result = { a: 3, b: 2, c: 3, d: 4 }

Passing arguments to function using spread operator

Let's say we have an add function that takes two arguments and returns the sum. To pass argument we generally write something like the following.

function add(x, y) {
  return x + y;
}
const result = add(1, 2);

We can achieve the same result using spread operator.

function add(x, y) {
  return x + y;
}
const args = [1, 2];
const result = add(...args);