Arrow Functions
An arrow function is a shorter way to write a function in JavaScript. It is most useful when we use a function as a value.
Basic Syntax of Arrow Functions
An arrow function drops the function keyword and puts an arrow (=>) between the parameters and the body:
const mean = (x, y) => {
return (x + y) / 2;
};
Syntax Details
-
Parameters: The parameters go in parentheses. With exactly one parameter we can leave the parentheses out. With no parameters, or with more than one, we have to write them.
-
Function Body: The body comes after the arrow (
=>). If the body is more than one statement, we wrap it in curly brackets:-
If the body is a single expression, we do not need the curly brackets, and the expression is returned without writing
return. -
If that single expression is an object literal, we wrap the object in parentheses so JavaScript does not read its curly brackets as the function body.
-
const user = username => ({ username });
// This simplifies:
const user = (username) => {
return { username };
};
Arrow Functions with Higher-Order Functions
We often pass arrow functions to higher-order functions, because the syntax is short:
const numbers = [1, 2, 3, 4, 5, 6, 7];
const evens = numbers.filter(x => x % 2 === 0);
console.log(evens); // Outputs: [2, 4, 6]
Differences from Regular Functions
An arrow function is not just a shorter function expression. There are a few real differences. One of them is that an arrow function does not have an arguments object. When you need to work with an unspecified number of arguments, use rest parameters instead.