Search code examples
javascriptreactjsecmascript-6returnarrow-functions

Why wrap Arrow function body in parentheses


In a survivejs code example I encountered a function with a body wrapped in parentheses:

export default () => (
  <ul>
      {notes.map(note =>
          //some code
      )}
  </ul>
)

MDN explains it like this:

// Parenthesize the body of function to return an object literal expression:
params => ({foo: bar})

Trying to figure out what this actually means in a real world use case. Car analogies welcome (;


Solution

  • The MDN declaration is used to return an object literal. But I think you want to know why some people put the return instruction in parentheses regardless of the object literals.

    A Bit Theory

    In JavaScript are semicolons optional. This can cause some errors if you dont know the behavior of the Automatic Semicolon Insertion.

    When you have a return with a line break it will return an undefined

    const add = (x, y) => {
      return
        x + y
    }
    
    console.log( add(1, 1) )  // undefined

    The equivalent after the Automatic Semicolon Insertion does some magic is:

    const add = (x, y) => {
      return;
      x + y;
    };
    
    console.log( add(1, 1) );

    But what if the line break is a must, for example, for readability.. The solution is to wrap the expression into parentheses.

    const add = (x, y) => {
      return (
        x + y
      )
    }
    
    console.log( add(1, 1) ) // 2

    Your Use Case

    To get rid of the parentheses we could lift up the <ul> tag directly after the =>.

    const functionName = xs => <ul>
        {xs.map(note =>
            //some code
        )}
    </ul>
    

    But now it is not really readable anymore.. so we should reinsert the parentheses quickly

    const functionName = xs => (
        <ul>
            {xs.map( x =>
                //some code
            )}
        </ul>
    )