Search code examples
javascriptcallbacknotation

JS - On a callback, What's the difference of using parenthesis and / or brackets on it?


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?


Solution

  • 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).