Arrow function without curly braces

前端 未结 7 1215
生来不讨喜
生来不讨喜 2020-11-22 10:52

I\'m new to both ES6 and React and I keep seeing arrow functions. Why is it that some arrow functions use curly braces after the fat arrow and some use parentheses? For exam

7条回答
  •  夕颜
    夕颜 (楼主)
    2020-11-22 11:21

    To answer a duplicate post(question posted here), just for reference for others:

      var func = x => x * x;                  
        // concise body syntax, implied "return"
    
        var func = (x, y) => { return x + y; }; 
        // with block body, explicit "return" needed
    

    For reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions#Function_body

    Also note: If you are returning an object literal as the result from a fat arrow function, then you must enclose the object in parentheses, e.g., myFunc = () => ({ data: "hello"}). You will receive an error if you omit the parentheses because the build tools will assume that the curly braces of the object literal are the start and end of a function body.

提交回复
热议问题