DEV Community

Discussion on: Arrow Function: Basics

Collapse
 
pentacular profile image
pentacular • Edited

If there is only 1 argument, we can skip parenthesis

Unless there's one argument which is destructured.

const q = ({ a = 1 }) => a;

If the function has only one statement, and the statement returns a value, we can remove the brackets and the return keyword.

Rather, if the function body is an expression, the value of the expression is returned.

Consider why the following is not legal -- it is one statement, but it is not a valid expression.

const r = () => return;

This is also why you need parentheses in the following case

const s = () => ({ a: 1 });
Collapse
 
bhagatparwinder profile image
Parwinder 👨🏻‍💻

I do consider both examples as edge cases but they are correct and valid. I have updated the article to showcase them. I appreciate the feedback.

Thanks for reading! ♥️

Collapse
 
pentacular profile image
pentacular

If the function has only one statement, and the statement returns a value, we can remove the brackets and the return keyword.

const greeting = () => "Hello World!";
console.log(greeting()); // Hello World

"Hello World!" is not a statement, and if it were, it would not return.

It is an expression, and it evaluates.

Thread Thread
 
bhagatparwinder profile image
Parwinder 👨🏻‍💻

Yep agreed. Corrected the post as I mentioned above.

Thread Thread
 
pentacular profile image
pentacular • Edited

Looking better, although

If the function body is an expression, it will return the expression, we can remove the brackets and the return keyword.

If it has {} or return, then the function body isn't an expression. :)

I think the simplest way to express it is that there are two distinct forms.

  1. () => expression;
  2. () => { ...; return value; }; // block of statements
Thread Thread
 
bhagatparwinder profile image
Parwinder 👨🏻‍💻

Your bullet point 2 is generally how folks write functions if they are not using shorthand. That is why my blog post starts with the example of an arrow function that has {} and return.

The shorthand is omitting the braces and return when there is one expression, Which is reflected by the fourth bullet point (or the part you just quoted). So at this point I am covering both the points you mentioned.

Thanks for the feedback.

Thread Thread
 
pentacular profile image
pentacular

Sure. The main thing is not to conflate expressions and statements. :)