ES6 Arrow functions in JavaScript
Arrow functions (also called “fat arrow functions”) are undoubtedly one of the more popular features of ES6.
It’s much shorter! We are able to omit the curly braces and the return statement due to implicit returns (but only if there is no block — more on this below).
Variations
1. No parameters
If there are no parameters, you can place empty parentheses before =>
() => 42
In fact, you don’t even need the parentheses!
_ => 42
2. Single parameter
With these functions, parentheses are optional:
x => 42 || (x) => 42
3. Multiple parameters
Parentheses are required for these functions:
(x, y) => x * y
4. Statements (as opposed to expressions)
In its most basic form, a function expression produces a value, while a function statement performs an action.
With the arrow function, it is important to remember that statements need to have curly braces. Once the curly braces are present, you always need to write return
as well.
Here is an example of the arrow function used with an if statement:
var feedTheCat = (cat) => {
if (cat === 'hungry') {
return 'Feed the cat';
} else {
return 'Do not feed the cat';
}
}
5. “Block body”
If your function is in a block, you must also use the explicit return
statement:
var addValues = (x, y) => {
return x + y
}
6. Object literals
If you are returning an object literal, it needs to be wrapped in parentheses. This forces the interpreter to evaluate what is inside the parentheses, and the object literal is returned.
x =>({ y: x })