Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

JavaScript React Basics Understanding State Update State Based on Previous State

Joseph Butterfield
.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
216,165 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
216,165 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.