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 Components (2018) Managing State and Data Flow Update State Based on a Player's Index

Moe Ghashim
Moe Ghashim
11,109 Points

Why did we wrap the code block in handleScore with parenthesis?

In handleScore

 handleScore = (delta, index) => {
    this.setState(prevState => ({
      score: (prevState.players[index].score += delta),
    }))
  }

we wrapped the arrow function with parenthesis. When I was testing, I forgot to do so and I wrote it like this:

 handleScore = (delta, index) => {
    this.setState(prevState => {
      score: prevState.players[index].score += delta
    })
  }

I got this error https://www.dropbox.com/s/rncspqo1wgaiivd/Screenshot%202019-03-24%2009.31.52.png?dl=0 Can you explain what the parenthesis do here?

1 Answer

Steven Parker
Steven Parker
229,982 Points

Arrow functions can be defined two ways: the arrow can be followed by a single expression that is evaluated and returned, or it can be followed by a code block in braces that contains statements to be executed.

The parentheses make it clear that this is the first type, and the expression is an object literal to be returned.

Without the parentheses, it is misinterpreted as the second type, and the property name is assumed to be an inappropriate statement label instead.