When should I use `return` in es6 Arrow Functions?

后端 未结 5 2218
后悔当初
后悔当初 2020-11-21 05:40

The new es6 arrow functions say return is implicit under some circumstances:

The expression is also the implicit return value of that fun

5条回答
  •  抹茶落季
    2020-11-21 06:06

    Here's another case that gave me some trouble.

    // the "tricky" way
    const wrap = (foo) => (bar) => {
      if (foo === 'foo') return foo + ' ' + bar;
      return 'nofoo ' + bar;
    }
    

    Here we define a function returning an anonymous function.The "tricky" bit is that the function body for the outer function (the part begining with (bar) => ...) visually looks like a "block", but it's not. Since it's not, implicit return kicks in.

    Here's how wrap would execute:

    // use wrap() to create a function withfoo()
    const withfoo = wrap('foo');
    // returns: foo bar
    console.log(withfoo('bar'));
    
    // use wrap() to create a function withoutfoo()
    const withoutfoo = wrap('bar');
    // returns: nofoo bar
    console.log(withoutfoo('bar'));
    

    The way I unpacked this to make sure I understood it was to "unarrowify" the functions.

    Here's the semantic equivalent of the first code block, simply making the body of wrap() do an explicit return. This definition produces the same results as above. This is where the dots connect. Compare the first code block above with the one below, and it's clear that an arrow function itself is treated as an expression, not a block, and has the implied return.

    // the explicit return way
    const wrap = (foo) => {
      return (bar) => {
        if (foo === 'foo') return foo + ' ' + bar;
        return 'nofoo ' + bar;
      }
    }
    

    The fully unarrowified version of wrap would be like this, which while not as compact as the fat arrowed up version, seems a lot easier to comprehend.

    // the "no arrow functions" way
    const wrap = function(foo) {
      return function(bar) {
        if (foo === 'foo') return foo + ' ' + bar;
        return 'nofoo ' + bar;
      };
    };
    

    In the end, for others that may have to read my code, and future me, I think I'd prefer to go the non arrow version which can be comprehended visually at first glance, rather than the arrow one which takes a fair bit of thought (and in my case experimentation) to grok.

提交回复
热议问题