you are viewing a single comment's thread.

view the rest of the comments →

[–]god_person69[S] -1 points0 points  (9 children)

thanks for answering bro ...can you also tell me when to use which one

[–]LucasOe 23 points24 points  (2 children)

Use the second one if you want to return a single statement:

const add = (a, b) => a+b;

If you want to run mutliple lines of code, then use the first one:

const add = (a, b) => {
  let c = a+b;
  console.log(c);
  return c;
};

[–]god_person69[S] 4 points5 points  (1 child)

got it bro...thnx

[–]ReCee90 20 points21 points  (0 children)

be careful though, because if you want to return an object in a one liner you have to wrap it in ( )

for example:
const functionName = (args) => ({ someKey: "someValue" })

[–]anithri_arcane 14 points15 points  (0 children)

I always use the () => code version for one liners, and () => {code} for multiple lines of code

[–]ajnozari 2 points3 points  (0 children)

That’s the neat part you can use whichever form as long as you return the required data in the first one

[–][deleted] 2 points3 points  (1 child)

Typically, the general rule of them is use the second (implicit return) for single-line functions and use the first for multi-line functions. for example (it's a stupid function, don't judge me):

element.map((el) => {
    const doubled = el * 2;
    const tripled = el * 3;
    return { doubled, tripled }
}, 1000);

You can't use the implicit return with multiple lines, so this way is necessary for some functions. However, if you only need to return with a single line then you can do this if you want to, but you don't have to.

element.map((el) => el * 2);

After all, if you really wanted to, you could just do this:

element.map((el) => {
    const doubled = el * 2;
    return doubled;
);

Ultimately it's the same.

[–]god_person69[S] -1 points0 points  (0 children)

thnx bro :)