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;
})
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:
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
: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 explicitreturn
:The basic syntax of fat arrow functions is:
However:
You can omit the
()
around the argument list if there's exactly one argument:You can omit the
{}
around the function body if you only have a single expression in the body, in which casereturn
is also implied: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.:(foo) => 'bar';
does exactly the same thing as
If your function is multiline, use the second form.
Here are some docs: MDN Arrow function
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