Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript React by Example Building the Application Writing a Handler to Confirm Guests

Use of spread operator in this lesson?

I've read the teachers notes, Googled a few examples, and understand how to use the spread operator but am not understanding how it is being used in this lesson.

Guil uses ...guest instead of name: guest.name

Guil says the spread operator basically just transfers the keys and values from one object to another. This is the part that confuses me Can anyone provide an example?

Event Handler

toggleIsConfirmedAt = indexToChange =>
    this.setState({
      guests: this.state.guests.map((guest, index) => {
        if(index === indexToChange) {
          return {
            name: guest.name,
            isConfirmed: !guest.isConfirmed
          }
        }
      })
    });

State Object

guests: [
      {
        name: 'Fred Flinstone',
        isConfirmed: false
      },
      {
        name: 'Barney Rubble',
        isConfirmed: true
      },
      {
        name: 'Great Gazoo',
        isConfirmed: true
      }
    ]

1 Answer

Brendan Whiting
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Brendan Whiting
Front End Web Development Techdegree Graduate 84,738 Points

I think the main benefit of using the spread operator here is that it's more future-proof. He says "if we ever add more properties to this object for any reason, we'd have to come, find this place again, and change it.".

So here's an example. Let's say were were not using the spread operator, and composing the object this way:

return {
    name: guest.name,
    isConfirmed: !guest.isConfirmed
}

So let's say later on, we add another field - isVegetarian - to the guest objects. As it is currently, when this object is returned, the isVegetarian field would be stripped out of the object, because we're explicitly only adding the fields name and isConfirmed. But if we used the spread operator, it automatically puts out all the current keys and values of that object - name, isConfirmed, isVegetarian, and anything else, then the next line isConfirmed: !guest.isConfirmed overrides the value that came from the spread operator.

Thanks Brendan, You always come thru for me. It seems simple now that you explained it this way.