Also known as Fat Arrow Functions. They're a clean and consise way to write function expressions, e.g. function() {}
.
Arrow Functions can remove the need of function
, return
and {}
when defining functions. They are one-liners, similar to Lambda Expressions in Java or Python.
const queue = ['Dave', 'Sarah', 'Sharon'];
const nextCustomer = () => queue[0];
console.log(nextCustomer()); // 'Dave'
_x000D_
If multiple statements need to be made within the same Arrow Function, you need to wrap, in this example, queue[0]
in curley brackets {}
. In this case the return statement cannot be omitted.
const queue = ['Dave', 'Sarah', 'Sharon'];
const addCustomer = name => {
queue.push(name);
};
addCustomer('Toby');
console.log(queue); // ['Dave', 'Sarah', 'Sharon', 'Toby']
_x000D_
You can omit {}
from the above.
When there is a single parameter, the brackets ()
around the parameter can be omitted.
const addNumbers = (x, y) => x + y
console.log(addNumbers(1, 5)); // 6
_x000D_
const fruits = [
{ name: 'Apple', price: 2 },
{ name: 'Bananna', price: 3 },
{ name: 'Pear', price: 1 }
];
If we wanted to get the price of every fruit in a single array, in ES5 we could do:
fruits.map(function(fruit) {
return fruit.price;
}); // [2, 3, 1]
In ES6 with the new Arrow Functions, we can make this more concise:
fruits.map(fruit => fruit.price); // [2, 3, 1]
Additional information on Arrow Functions can be found here.