search

Home  >  Q&A  >  body text

When should you use return statement in ES6 arrow functions?

<p>The new ES6 arrow functions say that in some cases, <code>return</code> is implicit: </p> <blockquote> <p>This expression is also the implicit return value of the function. </p> </blockquote> <p>In what situations do I need to use <code>return</code> in an ES6 arrow function? </p>
P粉771233336P粉771233336462 days ago627

reply all(2)I'll reply

  • P粉258083432

    P粉2580834322023-08-23 11:00:08

    I understand this rule of thumb...

    The candidates are:

    // 平方根
    value => Math.sqrt(value)
    
    // 求和
    (a,b) => a+b

    For other operations (if multiple lines of code are required, an explicit return value is required)

    reply
    0
  • P粉012875927

    P粉0128759272023-08-23 00:47:21

    Jackson partially answered this question in a similar question:

    I would like to add the definition of block:

    Example:

    // 返回:undefined
    // 解释:一个空的带有隐式返回的块
    ((name) => {})() 
    
    // 返回:'Hi Jess'
    // 解释:没有块意味着隐式返回
    ((name) => 'Hi ' + name)('Jess')
    
    // 返回:undefined
    // 解释:块内需要显式返回,但是缺少了
    ((name) => {'Hi ' + name})('Jess')
    
    // 返回:'Hi Jess'
    // 解释:块内有显式返回
    ((name) => {return 'Hi ' + name})('Jess') 
    
    // 返回:undefined
    // 解释:一个包含单个标签的块。没有显式返回。
    // 更多信息:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/label
    ((name) => {id: name})('Jess') 
    
    // 返回:{id: 'Jess'}
    // 解释:隐式返回表达式 ( ),其求值为一个对象
    ((name) => ({id: name}))('Jess') 
    
    // 返回:{id: 'Jess'}
    // 解释:块内有显式返回对象
    ((name) => {return {id: name}})('Jess')

    reply
    0
  • Cancelreply