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 trialJoseph Butterfield
Full Stack JavaScript Techdegree Graduate 16,430 PointsWhy 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
231,269 PointsThe 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".
Joseph Butterfield
Full Stack JavaScript Techdegree Graduate 16,430 PointsJoseph Butterfield
Full Stack JavaScript Techdegree Graduate 16,430 PointsOooooh... I see that. I was racking my head over this. What would that be called? As in, where can I find documentation on use case?
Steven Parker
231,269 PointsSteven Parker
231,269 PointsAnytime 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.
Chris Adams
Front End Web Development Techdegree Graduate 29,423 PointsChris Adams
Front End Web Development Techdegree Graduate 29,423 PointsOh, I was curious about this too! Thanks for pointing that out, Steven!