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

后端 未结 5 1040
梦谈多话
梦谈多话 2020-12-07 04:40

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\')
          


        
相关标签:
5条回答
  • 2020-12-07 05:03

    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)
    
    0 讨论(0)
  • 2020-12-07 05:11

    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>
    )
    
    0 讨论(0)
  • 2020-12-07 05:17

    (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

    0 讨论(0)
  • 2020-12-07 05:20

    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;
    })
    
    0 讨论(0)
  • 2020-12-07 05:22

    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
    
    0 讨论(0)
提交回复
热议问题