Syntax of fat arrow functions (=>), to use or not to use {} around the body

I am looking at this code - https://facebook.github.io/react-native/docs/network.html

return fetch('https://facebook.github.io/react-native/movies.json')
      .then((response) => response.json())
      .then((responseJson) => {
        return responseJson.movies;
      })

From what I understand .then((response) => response.json()) translates into:

.then(function(response) {
    return response.json()
}

but I can't figure out what does this translate into? there is an extra {} in it

.then((responseJson) => {
        return responseJson.movies;
      })

Answers:

Answer

If you don't wrap the body of an arrow function with curly brackets, it will evaluate the expression and return the result implicitly. If you wrap it with curly brackets, the result is not implicitly returned and you have to do it explicitly.

For this reason, the second part 'equals' the following:

.then(function(responseJson) {
    return responseJson.movies;
})
Answer

The basic syntax of fat arrow functions is:

(arg1, arg2, ...) => { ... }

However:

  1. You can omit the () around the argument list if there's exactly one argument:

    arg => { ... }
    
  2. You can omit the {} around the function body if you only have a single expression in the body, in which case return is also implied:

    arg => arg.foo
    // means:
    (arg) => { return arg.foo; }
    

Since callbacks of the form function (arg) { return arg.prop; } are extremely common in Javascript, these two special cases to the syntax make such common operations extremely concise and expressive. E.g.:

arr.filter(foo => foo.bar)
Answer

(foo) => 'bar';

does exactly the same thing as

(foo) => {
  return 'bar';
};

If your function is multiline, use the second form.

Here are some docs: MDN Arrow function

Answer

Another tip - if using the implied return shorthand, i.e.:

foo => foo.bar

you are able to write the return expression as multi-line. The only catch is you must include () around the expression. This happens often in React, for example, to improve JSX readability

const myButton = props => (
  <Button color={props.color} >
    My Button text!
  </Button>
)
Answer

As a sidenote, if you want your function to return an object literal, you'll have to go with the extra curly braces and the explicit return:

foo => { bar: "baz" } // will not work!

This example will not work as the curly braces will not be interpreted as the delimiting characters of an object literal, but as the delimters of a block. Inside a block, bar: "baz" obviously is a syntax error. So to return { bar: "baz" } you need the xtra curly braces and the explicit return:

foo => { return { bar: "baz" } } // will work

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.