Arrow functions were introduced as part of ECMAScript 2015 (ES6) and provide a shorter way of writing functions.
They are heavily used throughout modern JavaScript and are particularly common
when working with array methods such as map(), filter(),
find() and reduce().
Although arrow functions provide a more compact syntax, they can perform the same tasks as traditional functions.
Traditional functions
Before arrow functions were introduced, functions were typically declared
using the function keyword.
Consider the following:
function double(number) { return number * 2; }
This function accepts a number and returns twice its value.
What arrow functions are
Arrow functions provide an alternative way of creating functions.
The previous example can be rewritten as:
const double = (number) => { return number * 2; };
The function behaves exactly the same way as the previous example.
The main difference is that the function keyword has been replaced
with the arrow operator (=>).
Single parameters
When an arrow function only accepts a single parameter, the parentheses around the parameter may be omitted.
const double = number => { return number * 2; };
This is functionally identical to the previous example.
Multiple parameters
If a function accepts multiple parameters, parentheses must be used.
Consider the following:
const add = (a, b) => { return a + b; };
In this example the function returns the sum of two values.
Implicit return values
If an arrow function contains a single expression, JavaScript can automatically return the result.
This means that both the braces and the return statement may be removed.
const double = number => number * 2;
This is the shortest form of an arrow function and is commonly used throughout modern JavaScript code.
Multiple statements
If a function contains more than one statement, braces must be used.
Consider the following:
const calculate = number => { number *= 2; number += 5; return number; };
Because multiple statements are being executed, the return
statement is required.
Arrow functions and array methods
Arrow functions are frequently used with array methods.
Consider the following array:
const numbers = [1, 2, 3, 4, 5];
The map() method can use an arrow function to double every value:
const result = numbers.map( number => number * 2 );
The output will be:
[2, 4, 6, 8, 10]
Arrow functions make these operations significantly easier to read.
When to use arrow functions
Arrow functions are ideal for short functions that are used only once.
They are particularly useful when working with array methods, event handlers and asynchronous code.
Since modern libraries and frameworks such as React make heavy use of arrow functions, understanding them is an important part of learning modern JavaScript.
