This page looks best with JavaScript enabled

Arrow Functions and `this` in Javascript

 ·   ·  ☕ 3 min read

Arrow functions have made our life much much easier. You can now refer to this without fearing the bogeyman.

How did we write functions in the dark ages?

Here’s a typical function.

1
2
3
4
5
6
function getSum(i, j) {
  // or const getSum = function(i,j) {
  return i + j;
}

console.log(getSum(3, 2)); // 5

The same functionality as arrow function -

1
2
3
const getSum = (i, j) => i + j;

console.log(getSum(3, 2)); // 5

Right off the bat you will see that arrow functions are assigned to variables, have an implicit return and structure wise do not different all that much from normal functions.

It goes deeper.

Context

Arrow functions provide dynamic context. The this variable refers to parent and is inherited from execution context, while it is local in regular functions.

This may not be a big deal view as-is, but this is massive in call-backs. In functions (nested functions in particular), this is super confusing.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
RestService.get = function (method) {
  var self = this;
  // self has values describing the service incl. url

  return new Promise(function (resolve, reject) {
    http.get(self.url + method, function (data) {
      resolve(data);
    });
  });
};

This can be rewritten to -

1
2
3
4
5
6
7
RestService.get = function (method) {
  return new Promise((resolve, reject) => {
    http.get(this.url + method, function (data) {
      resolve(data);
    });
  });
};

You should now be writing call backs using async/await. The above code is for direct comparison with the older way of writing functions.

Readable

Arrow functions are cleaner to read and easier to understand.

Many of the newer ES6 features make use of the arrow functions quite effectively.

Instead of doing this..

1
2
3
4
5
6
7
8
9
const fruits = [
  { name: "apple", color: "red" },
  { name: "orange", color: "orange" },
];
var fruitColors = fruits.map(function (fruit) {
  return fruit.color;
});

console.log(fruitColors); // [ 'red', 'orange' ]

.. you do this -

1
2
3
4
5
const fruits = [
  { name: "apple", color: "red" },
  { name: "orange", color: "orange" },
];
var fruitColors = fruits.map((fruit) => fruit.color);

More Readable

If you do function chaining, you would have seen this..

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
func1
  .fetch()
  .then(function () {
    func2();
  })
  .then(function () {
    func3();
  })
  .done(function () {
    func4();
  });

Now, this can be -

1
2
3
4
func1()
  .then(() => func2())
  .then(() => func3())
  .done(() => func4);

Use Arrows Responsibly

Arrow functions do not have their own bindings to this, super, and arguments keywords - they are designed to be lighter as compared to normal functions. They cannot be used in generators, and constructors.

Stay in touch!
Share on

Prashanth Krishnamurthy
WRITTEN BY
Prashanth Krishnamurthy
Technologist | Creator of Things