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 Basics (2018) Understanding State Remove Items From State

handleRemovePlayer function

I am confused on when to use a return and when not to in writing a function for a state in this example when we created the handleRemovePlayer function, why did we use a return{}? But in the previous functions for increment score and decrement score we didn't use a return{} in the function?


no return used and also 2 parentheses ,this.setState( prevState =>( { } ) );

addScore = ()=>{
      this.setState( prevState =>({
          score:prevState.score + 1

with the return

handleRemovePlayer = (id) =>{
        this.setState( prevState => {
                players: prevState.players.filter()
Robin Siegl
Robin Siegl
11,157 Points

I think it's because in the first code block you just set the score (don't ned to get anything back) and on the second code block you probably need to get the value back. Maybe i'm wrong here, but i hope someone can give a clear answer to this.

2 Answers

In arrow functions you can have an explicit or implicit return, but it's always returning something (even undefined). The second code you gave can be rewritten like this:

handleRemovePlayer = (id) =>{
        this.setState( prevState => ( {
                players: prevState.players.filter()
            } )

The extra pair of parentheses around { players: prevState.players.filter() } are needed so the interpreter doesn't read them as the initial braces of a code block, rather than an object literal, which is what we want.

Robin is right. You use return when you want something back. In the first example, we're just updating the prev state by adding 1 on click. In the second, we are filtering to remove the deleted player and return the rest of the players that were not deleted.

Thanks Robin and Kod, now it makes sense