JavaScript React Basics 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
207,988 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
207,988 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.