JavaScript React Components Managing State and Data Flow Update State Based on a Player's Index

Moe Ghashim
Moe Ghashim
10,426 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
171,327 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.