Arrow Functions Return Rules in JavaScript
There are 2 ways for returning values in arrow functions:
- Explicit Return
- Implicit Return
1. Explicit Return
What is Explicit Return?
A function is returned values using the return keyword, it’s called an explicit return.
The Rules of Explicit Return
You must use an explicit return statement in a block body.
Example
// Single-line
const explicit = (value) => { return value; }
// Multi-line
const explicit = (value) => {
return value;
}
2. Implicit Return
What is Implicit Return?
A function is returned values without using the return keyword, it’s called an implicit return.
The Rules of Implicit Return
You must use an implicit return in a concise body.
Example
// Single-line
const implicit = (value) => value;
// Multi-line
const implicit = (value) => (
value
);
Issue Returning Objects
When using implicit returns, object literals must be wrapped in parenthesis so that the curly braces are not mistaken for the opening of the function’s body.
const implicit = () => { value: 1 };
implicit(); // undefined
const implicit = () => ({ value: 1 });
implicit(); // { value: 1 }
Parens Rules
Arrow functions can omit parentheses when they have exactly one parameter.
// Arrow Functions, with parentheses
const myFunction = (p) => {}
// Arrow Functions, without parentheses
const myFunction = p => {}
In all other cases (multiple parameters), the parameter(s) must be wrapped in parentheses.
// Arrow Function, with parentheses
const myFunction = (p1, p2) => {}
References
Thanks for reading ❤ Say Hello! Twitter | Github | LinkedIn | Facebook | Instagram