1

I came across the following code in a GraphQL-related post. Why are there brackets outside of the curly brackets in the fields parameter and what does this mean?

var PersonType = new GraphQLObjectType({
  name: 'Person',
  fields: () => ({
    name: { type: GraphQLString },
    bestFriend: { type: PersonType },
  })
});

The following are the function expressions / declarations that I am aware of:

Standard Named Functions

function sayHello() {
    alert("hello!");
};

ES6 Anonymous Functions

() => {
    alert("hello!");
};

Self Invoked Functions

(function sayHello() {
    alert("hello!");
})();

Self Invoked ES6 Anonymous Functions

(() => {
    alert("hello!");
})();

As far as I'm aware, the fields function does not fit any of the above.

ptk
  • 6,835
  • 14
  • 45
  • 91
  • 1
    Reading [the documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions) is always useful. – Teemu Sep 28 '18 at 04:23
  • Ahhh understood. @Teemu thanks for the link. I see it now under "Advanced Syntax". Found it a little hard to convey my question into words to Google but now its perfectly obvious I should've looked deeper into arrow functions. – ptk Sep 28 '18 at 04:25

3 Answers3

3

The parenthesis are there to make the function return the object without having to wrap the entire object in braces with a return.

For example this doesn't work:

var PersonType = new GraphQLObjectType({
  name: 'Person',
  fields: () => {                  // interpreted as a block not an object
    name: { type: GraphQLString },
    bestFriend: { type: PersonType },
  }
});

because the {} would be interpreted as a block, when you want to return an object.

You could do this:

var PersonType = new GraphQLObjectType({
  name: 'Person',
  fields: () => {
    return { name: { type: GraphQLString },
             bestFriend: { type: PersonType },
           }
  }
});

but that doesn't seem as nice as just using the parenthesis which will cause the function to return the object.

Mark
  • 90,562
  • 7
  • 108
  • 148
2

The returning object is wrapped in '()' parentheses so that curly braces are not considered as function body but rather an object.

1

If the parentheses weren't there, what would it look like?

fields: () => {
  name: { type: GraphQLString },
  bestFriend: { type: PersonType },
}

Well that looks an awful lot like function block syntax. And in fact, that's what interpreters will assume, and then throw syntax errors when they see weird key: value syntax where standard expressions are expected.

In other words, the parentheses are there to indicate that the function returns an object, and that the curly braces should not be interpreted as enclosing a code block.

Matt Mokary
  • 717
  • 6
  • 13