Uses of the Spread Operator in Objects.

Yoel Macia
2 min readNov 29, 2019

--

As a prolongation of the previous article, in which we talked about the uses of the Spread Operator in Arrays, today we will talk about the use in Objects.

Photo by marianne bos on Unsplash

In MDN terms, the Spread syntax allows an iterable as an array or string expression 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 pairs of key values (for object literals) are expected.

We are going to talk about objects.

The first use of the spread operator is to copy into the content of an object, avoiding the use of Object.assign().

let cores = { cor1: "Vermello", cor2: "Yellow", cor3: "Blue" };
let newCores = { ...cores }

The second use is to add elements from one object to other object.

let coresToAdd = { cor1: "Vermello", cor2: "Yellow", cor3: "Blue" };
let cores = {cor4: "Ouro", cor5: "Branco”, ...coresToAdd};

The third use is to concatenate objects

let coresMain = { cor1: "Vermello", cor2: "Yellow", cor3: "Blue" };
let coresSecondary = {cor4: “Ouro”, cor5:“Branco”, cor6:“Negro”};
coresMain = {...coresMain, ...coresSecondary};

The fourth use is to pass the elements of an object as arguments of a function.

function printCores({ mainCor, secondCor }) {console.log(`Cor : ${mainCor} ${secondCor}`);}let corObj = { mainCor: "Vermello", secondCor: "Amarelo" };printCores(corObj); // Vermello Amarelo

Thank you very much and keep coding!!!

Yoel

I often share more code tips on my Instagram you can say hello to me on my Twitter or see how i code in my Github.

--

--

Yoel Macia

Writing daily about Javascript. Creator of the publication The Javascript Adventure.