6.5 Arrow Function
The predicate we passed to find in the previous lesson works, but the syntax is verbose. ES6 brings arrow functions, a shorter way to write callbacks. Any time you want to pass a function as an argument to another function or method, arrow functions are usually the cleanest choice.
// Before (function expression)
courses.find(function (course) {
return course.name === "a";
});
// Step 1: remove the keyword 'function' and add =>
courses.find((course) => {
return course.name === "a";
});
// Step 2: a single parameter → drop the parentheses
courses.find(course => {
return course.name === "a";
});
// Step 3: a single return statement → drop {} and return
courses.find(course => course.name === "a");
The shortening rules
- Replace
function (params)with(params) =>. - If the function takes exactly one parameter, the parentheses around it become optional.
- If the body is a single expression that is returned, the curly braces and the
returnkeyword can both be dropped. - With zero parameters, you must keep the parentheses:
() => ....
Arrow functions are everywhere in modern JavaScript: array methods like find, map, filter and reduce, event handlers, promises, you name it. They also change how this behaves, but that is a topic for a later lesson. See you in the next video, where we look at deleting elements from an array.