-1

I'm currently using react and I have noticed that the behaviour may change depending on how a callback is used. (Not sure if this is called notation). To illustrate my question, let's use Array.map().

Array.map(el=> return el.name);
Array.map((el)=> return el.name);
Array.map((el)=> {return el.name});
Array.map(el=> {return el.name});

Are these four cases correct? What is the expected behaviour of each of them? Is there any that can be used "safely" always so it does bring up grammar errors?

Germán
  • 1,007
  • 1
  • 7
  • 20
  • There is no different in the functionality. First and second sentences aren't correct, if you only have one line, don't use brackets and you can omit 'return'. There is another option using parenthesis that is useful tu return object. The one you use it's up to you and your code style. ESLint use variables parenthesis by default, because is more scalable. If you only has one line, don't use brackets, otherwise, use it. – Gabriel Rodríguez Flores Jul 01 '22 at 08:00
  • `=> return` is a syntax error, as you should've immediately noticed when trying these out – Bergi Jul 01 '22 at 08:01
  • "*I have noticed that the behaviour may change*" - no, it shouldn't. What exactly did you notice to change? – Bergi Jul 01 '22 at 08:05

1 Answers1

0

When you omit (curly)brackets then no need to write return because it will implicitly return right side, and when you use brackets then you need explicitly to return:

Array.map(el=> el.name); // Here you can omit return
Array.map(el=> { return el.name }); // But here you must explicitly return

Regarding input parameters(left side), when you have one parameter you can leave it without brackets, but having more than one parameters implies you to include brackets around them. In case when you are writing typescript, even with one parameter you need to include brackets because you must specify type(when type is not implicitly resolved).

Milos Pavlovic
  • 1,355
  • 1
  • 2
  • 7