1

I have understood the spread operator which is

let color_lawn = {
title: "lawn",
color: "#00FF00",
rating: 0

};

const rateColor1 = (color, rating) => (
{...color, rating} );

which returns a new object with the passed object and its whole properties and value in the function parameter which is in my case color which below will be

console.log(rateColor1(color_lawn, 5));

Now my Question is this: if above call to the function calls with

console.log(rateColor1(color_lawn, 5))

What i don't understand is the 5 if we saying return the copy of the object `( {...color, 5} );

Then how come rating changes to 5 when we did not use the rating: 5; or color.rating=5

Does this mean that rating is actually holding 2 things? 5 and pointing to the objects rating key.

Another example i understood perfectly is:

const rateColor = function(color, rating) {
return Object.assign({}, color, { rating: rating });

};

But i do not understand this const rateColor1 = (color, rating) => ( {...color, rating} ); one how the 5 is assigned to the rating.

Swiss bobo
  • 307
  • 1
  • 3
  • 11
  • 1
    This is just how the ES6 syntax works. The function *does* mention `rating`, which serves *both* as property name and its value at the same time. – trincot Mar 06 '21 at 09:17

1 Answers1

1

That's because { rating } is a shorthand for { rating: rating }.

So, you are asking for all the properties of color plus a property rating set to variable rating's value.

Francesco Colamonici
  • 1,147
  • 1
  • 10
  • 16