3

Inside map function why is the function defined with ( ) => ( ) instead of ( ) => { }

  {mylist.map((elem, index) => (
            <div key={elem.id}>
              <h2>{elem.title}</h2>
            </div>
          ))}
John
  • 131
  • 10
  • 2
    Because it's not using a block body, just wrapping a single expression. – jonrsharpe May 29 '22 at 15:19
  • @jonrsharpe Ok I accept your answer if the code would be in 1 line . As I know we can omit curly braces / brackets if the return statement is only 1 line . BUT we have multiple lines of code so { } should be used . – John May 29 '22 at 15:21
  • 5
    You can omit them if the return is only one _expression_, it can span multiple _lines_. – jonrsharpe May 29 '22 at 15:22
  • Lines do have syntax significance in JavaScript, it's not Python. – Pointy May 29 '22 at 15:29

1 Answers1

8

You can leave () out if you put everything in one line:

 {mylist.map((elem, index) => <div key={elem.id}><h2>{elem.title}</h2></div>)}

If you want to return something, but it take several lines, then you have to use ():

{mylist.map((elem, index) => (
    <div key={elem.id}>
        <h2>{elem.title}</h2>
    </div>
))}

Finally, when you want to perform something and THEN return the result, you need to use {}. You still need to care when you return something - if it takes several lines, you have to wrap it with():

{mylist.map((elem, index) => {
    const id = elem.id;
    const title = elem.title;
    return (
        <div key={id}>
            <h2>{title}</h2>
        </div>
    );
})}

For returning objects it's also a bit different: You can wrap your object into brackets: ({...}) or explicitly return it: () => { return { ... }}

Igor Gonak
  • 2,050
  • 2
  • 10
  • 17