ES6: Arrow Functions

Sara Gee
2 min readMay 20, 2016

--

Es6 arrow functions FTW!

An arrow function expression has a shorter syntax compared to function expressions and lexically binds the this value (does not bind its own this, arguments, super, or new.target). Arrow functions are always anonymous. MDN

Let’s start with a simple example of how arrow functions can help us eliminate the extra boilerplate from ES5.

Given an array of contacts, I am expecting the output to be the location in which Sara Gee lives. With my array of 4 friends, it is easy to forget where they all live!

const friends = [
{ first: ‘Sara’, last: 'Gee', location: 'California', occupation: 'Software Engineer' },
{ first: 'Zoe', last: 'Kravitz', location: 'California', occupation: 'Musician' },
{ first: 'Sara', last: 'Lizarbe', location: 'New York', occupation: 'Store Manager' },
{ first: 'Daenerys', last: 'Targaryen', location: 'Essos', occupation: 'Mother of Dragon' },
]

With a simple filter function, I am able to filter Sara Gee from our array of friends. Let’s see how this works with ES5.

const saraGeeLocation = friends
.filter(function(friend) {
return friend.last === 'Gee'
})
console.log(saraGeeLocation) // output: [ { first: ‘Sara’, last: 'Gee', location: 'California', occupation: 'Software Engineer' } ]

I am only expecting Sara’s location so let’s map our keys and obtain only the location.

const saraGeeLocation = friends
.filter(function(friend) {
return friend.last === 'Gee'
})
.map(function(occupation) {
return occupation.location
})
console.log(saraGeeLocation) // output: ['California']

With ES6, our code is clean, easy to ready, and takes up less real estate.

const saraGeeLocation = friends
.filter(friend => friend.last === 'Gee')
.map(occupation => occupation.location)
console.log(saraGeeLocation) // output: ['California']

We’ve significantly reduced the amount of code we had to write by using ES6's arrow function! If our logic are single statements, we do not need to include ‘return’ or curly braces. *Given a function with 2 or more arguments, we must enclose them in parentheses.

--

--