Arrow Function vs Function in JS

Arslan ur Rehman Iqbal
Jul 5 · 2 min read

One of the most popular features introduced in ES6 is the arrow function (also known as fat arrow function). It’s a concise way of defining function.

Consider the following example:

But that’s not the only reason why arrow functions are so popular.

The arrow function has resolved one very confusing aspect of JavaScript — the one I like to call the this pointer uncertainty.

Let’s first understand what the this pointer uncertainty is. Have a look at the code below:

What happened here?

In JavaScript, consider a function attached to an object. For that function, the this pointer points to the same object inside which the function is defined (jsObject in our case).

So, when our code looked for a variable named message in jsObject, it couldn’t find it. Let’s fix the code and add the message variable in our object.

Note the variable assignment in the object.

When we assigned a value to the internal message variable of jsObject, the this pointer was still pointing to the global object.

But earlier, when the same this pointer was used inside the function, it was pointing somewhere else, i.e. to our jsObject.

When functions are called in JavaScript, where the this pointer is going to point to is not determined by where the function definition is written. Instead, it’s how a function is called that matters.

Now, in a large application, it gets hard to keep track of the this pointer and the passing of the required value to the appropriate function. This is where the arrow function syntax comes in.

If you are accessing the this pointer in your function and you want it to point to the surrounding code of the function definition, use the arrow syntax.

Let’s write printMessage using the arrow syntax and see what happens.

Also, change the value of the internal message variable, so we know where the this pointer is pointing when we call the functions.

So that’s how the fat arrow function resolved the this pointer uncertainty issue.

Don’t assume, while using the arrow function, that the this pointer will always point to the global object.

It’s important to note that, when you’re defining functions using arrow functions, wherever the this pointer will point to totally depends on the surrounding code of the function definition.

Thank you for reading!

Better Programming

Advice for programmers.

Arslan ur Rehman Iqbal

Written by

Web Developer

Better Programming

Advice for programmers.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade