Why doesn't my arrow function return a value?

后端 未结 1 662
广开言路
广开言路 2020-11-22 02:28

I have an arrow function that looks like this (simplified):

const f = arg => { arg.toUpperCase(); };

But when I call it, I get und

相关标签:
1条回答
  • 2020-11-22 03:29

    When you use the function body version of an arrow function (with {}), there is no implied return. You have to specify it. When you use the concise body (no {}), the result of the body expression is implicitly returned by the function.

    So you would write that either with an explicit return:

    const f = arg => { return arg.toUpperCase(); };
    // Explicit return ^^^^^^
    

    or with a concise body:

    const f = arg => arg.toUpperCase();
    

    Examples:

    const f1 = arg => { return arg.toUpperCase(); };
    console.log(f1("testing"));
    
    const f2 = arg => arg.toUpperCase();
    console.log(f2("testing"));


    Slightly tangential, but speaking of {}: If you want the concise arrow's body expression to be an object initializer, put it in ():

    const f = arg => ({prop: arg.toUpperCase()});
    
    0 讨论(0)
提交回复
热议问题