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 Update State Based on Previous State

Joseph Butterfield
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Joseph Butterfield
Full Stack JavaScript Techdegree Graduate 16,430 Points

Why add the () outside the return statement when you omit the return {} syntax?

The Counter class contains the two increment/decrement methods. In the video, Guil shows two ways to write the methods.

--First with a return statement:

incrementScore = () => { this.setState( prevState => { return { score: prevState.score - 1 } }) }

--> returns object with updated score

--Then simplifies by omitting return statement:

incrementScore = () => { this.setState( prevState => ({ score: prevState.score + 1 })); }

--> return statement omitted, which should eliminate need for return {}, but why then add extra parenthesis around the object:

param => ( {/* object to return */} )

Omitting the return statement is cleaner, but why add the additional parenthesis on the outside? it breaks the syntax of omitting the return statement in an ordinary arrow function

Return statement:

this.setState( stateReferenceParam => { return { /* Object to return */ } } )

Should simply remove keyword and brackets "return {}":

this.setState( stateReferenceParam => { / * Object to update state */} )

but also adds an additional () around the object:

this.setState( stateReferenceParam => ( { / * Object to update state */} ) )

1 Answer

Steven Parker
Steven Parker
231,269 Points

The parentheses allow the braces to indicate a literal object. Without them, the braces would be interpreted as the code block of the other syntax that requires an explicit "return".

Steven Parker
Steven Parker
231,269 Points

Anytime you must add syntax to make your intentions clear to the system could be generically called "disambiguation".

This particular case is discussed on the MDN page on Arrow Functions under the heading Returning object literals.

Oh, I was curious about this too! Thanks for pointing that out, Steven!