Skip to content Skip to sidebar Skip to footer

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 xT

Solution 1:

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 keywordreturn { field: {/*etc.*/} }
}

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

Solution 2:

It's for clarity's sake for the compiler as well as for the reader. The field: syntax in your example appears to be an unambiguous giveaway that this is an object literal, but take this code for instance:

letf = () => {
  field: 'value'
}

console.log(f()) //=> undefined

You would expect this to log an object with field set to 'value', but it logs undefined. Why?

Essentially, what you see as an object literal with a single property, the compiler sees as a function body (denoted by opening and closing curly braces, like a typical function) and a single label statement, which uses the syntax label:. Since the expression following is it just a literal string, and it is never returned (or even assigned to a variable), the function f() effectively does nothing, and its result is undefined.

However, by placing parentheses around your "object literal," you tell the compiler to treat the same characters as an expression rather than a bunch of statements, and so the object you desire is returned. (See this article on the Mozilla Development Network, from the comments section.)

letg = () => ({
  field: 'value'
})

console.log(g()) //=> { field: 'value' }

Post a Comment for "Es6 Fat Arrow And Parentheses `(...) => ({...})`"