Arrow functions are my personal favourite addition to Javascript that came along with ES6. Find out how to use them.
To fully appreciate the power and elegance of the arrow function, let’s take a quick look at a simple example written both ways.
// Example pre-ES6 function
function double(number){
return number * 2
}
// ES6 arrow function
const double = number => number * 2
As you can see, we swap three lines for one while retaining readability.
The rules to remember are:
- Remove
function
and add=>
after the argument(s) - If there’s a single argument, you can remove the brackets
()
around it - If there’s a single expression, you can remove the curly braces
{}
and thereturn
keyword (it’ll be an implicit return)*
*If you have a single expression but it’s particularly long, you may choose to keep the curly braces and have it on it’s own line like you would in a traditional function
.
With traditional function
s, when using anonymous functions within it (such as array.map
) the this
keyword does not refer to the original object. You would typically need to bind this
or self
prior to that anonymous function.
Arrow functions, however, benefit from lexical this
. Using this
inside of an arrow function refers to the context surrounding it (the outer level). It essentially makes this
work as we would expect it to.