How To Use Arrow Functions In JavaScript | ES6 | ES2015

faraz amiruddin
4 min readJun 30, 2017

--

I’ve been working with JavaScript for some time now. My first introduction to the language came via a framework called Meteor. At the time, Meteor had already implemented polyfills which meant that you could write ES6 out of the box. That being said, I didn’t know what ES6 even was or why I should care.

The way I like to think of ES6 is a version of JavaScript. Before ES6 was ES5. After ES6 will be ES7…etc. With each new version of JavaScript comes some new set of features, which may change the way things work or introduce new concepts.

I’d like to share what I’ve learned along the way and things that I find useful. I’ll wrap up at the end with a couple real world examples.

Arrow Functions

Arrow functions are a shorthand way to write functions in JavaScript. As you go along, you’ll find that ES6 features are a lot of syntactic sugar — which simply means ways do things we normally do with less code.

Let’s take a look at an example of a function:

var sayHello = function (name) {
return 'Hello ' + name;
}

In this example, we create the function sayHello that returns the string ‘Hello’ + the name you provide. Pretty straightforward.

Now let’s rewrite the above as an arrow function.

const sayHello = (name) => {
return 'Hello ' + name;
}

For this mini lesson, I won’t be getting into const vs var (maybe I’ll make another lesson explaining that)

The two code examples produce exactly the same output. Instead of writing the function keyword we use a fat arrow => to indicate the start of the function body.

You might think that this looks confusing and begin to wonder why you do this for such a small gain (code length).

Well, it gets better thanks to some cool more syntactic sugar.

Omitting The Parentheses

A handy trick that arrow functions provide is the ability to omit the parentheses ONLY if your function takes EXACTLY ONE argument.

Notice that there is only one cat in this picture.

I’ll repeat that. You can only omit the parentheses of an arrow function if your function takes EXACTLY ONE argument. Not zero, not two. Only one.

Let’s rewrite our sayHello function without the parentheses.

const sayHello = name => {
return 'Hello ' + name;
}

2 characters less! Yay!

Now, you might think this still might not be enough of a reason to use arrow functions. But there’s more sugar!

Implicit Return

Another shorthand we can use is the implicit return. If your function returns only one expression, we can omit the return keyword and the {} of the function body.

Since, 'Hello ' + name; is only one expression, we can take advantage of implicit return.

const sayHello = name => 'Hello ' + name;

Nice. I use this shorthand version a lot. I personally like less code that is understandable.

If you’re still not convinced about arrow functions, let’s talk about one last thing that makes them great and finish with a some real world examples.

Lexical This

If you’re coming from ES5 land, you are probably used to seeing statements like .bind(this) or var that = this;

The reason we need to use statements the above statements is because we need to bind this to the current functions execution context.

Put simply, JavaScript doesn’t know which this you’re referring to when you are using nested functions. Check out the following example:

function Car() {
this.speed = 0;

setInterval(function () {
this.speed += 10;
}.bind(this), 1000);
}
var myCar = new Car();setTimeout(function () {
console.log(myCar.speed);
}, 3000); // logs 30

In this example, we are creating a Car object with one field of speed. When we create a new instance of Car we immediately call setInterval which will run every second. setInterval increases the speed field of the Car by 10 every second.

We create an instance of Car and assign it to the variable myCar, and then we call a setTimeout and console.log(myCar.speed) after 3 seconds. (If you run this, you will see 30 in your console)

Because we are using a traditional function, notice that we have to bind(this) in order keep this pointing to the Car and not the function we pass to setInterval.

Arrow functions don’t create it’s own this, so we don’t have to worry about binding this . Let’s rewrite our Car constructor using an arrow function.

function Car() {
this.speed = 0;

setInterval(() => {
this.speed += 10;
}, 1000);
}
var myCar = new Car();setTimeout(function () {
console.log(myCar.speed);
}, 3000); // logs 30

No more bind(this) or var that = this or var self = this !

Real World Examples

To wrap up this mini lesson, I’ll share some real world examples where I use arrow functions.

Array Helpers

You might be familiar with an ES6 array helpers like .map() which are a great place to use arrow functions.

const numbers = [1, 2, 3, 4, 5];const doubledNumbers = numbers.map(number => number * 2);console.log(doubledNumbers); // [2, 4, 6, 8, 10]

Promises

When working with async fetching of data, you might have also come across Promises (also new to ES6!). Promise chains are a great place to use arrow functions as well!

fetch('https://jsonplaceholder.typicode.com/posts/1')
.then(response => response.json())
.then(json => console.log(json))
.catch(error => console.log(error));

If you enjoyed this post please 👏 👏 👏 and share.

You can follow me on twitter @farazmiruddin

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

faraz amiruddin
faraz amiruddin

Written by faraz amiruddin

software engineer. building retro.app in public. love react x firebase.

Responses (1)

Write a response