Search code examples
javascriptreactjsecmascript-6graphqlrelay

ES6 Fat Arrow and Parentheses `(...) => ({...})`


I've been working through some Graph QL/React/Relay examples and I ran into some strange syntax.

When defining the fields in Graph QL Objects the following syntax is used:

const xType = new GraphQLObjectType({
  name: 'X',
  description: 'A made up type for example.',
  fields: () => ({
    field: {/*etc.*/}
  })
});

From what I gather this is just defining an anonymous function and assigning it to xType.fields. That anonymous function returns the object containing the field definitions.

I'm assuming with however the Graph QL schema mechanism works this has to be defined as a function returning an object rather than simply an object. But the part that has me confused is the parenthesis around the curly braces.

Is this to differentiate an object definition from a function definition? Is it for clarity's sake for the reader?

The only similar syntax a google search has found is in the airbnb style guide where it seems to be a readability/clarity thing.

Just looking for confirmation or an explanation beyond my assumptions as I start to play around with Graph QL a little more.


Solution

  • fields: () => ({
      field: {/*etc.*/}
    })
    

    is a function that implicitly returns an object (literal). Without using () JavaScript interpreter interprets the {} as a wrapper for the function body and not as an object.

    Without using parens: (), the field: ... statement is treated as a label statement and the function returns undefined. The equivalent syntax is:

    fields: () => { // start of the function body
       // now we have to define an object 
       // and explicitly use the return keyword
       return { field: {/*etc.*/} }
    }
    

    So parents are not there for clarity. It's there for using implicit-returning feature of arrow functions.