Arrow functions in JavaScript

One of very, very nice ES6 capabilities are arrow functions. Using them, we can creae shorter, cleaner code, and also avoid important issues with this keyword – I wrote about this keyword in one of some ealier posts. This time I would like to write few sentences about arrow functions. If you do not know them yet, you should get to know them as soon as possible.

First of all – what is arrow function? According to official documentation, is shorter form of anonymous functions. But not only that. To use arrow function, we must only use argument, arrow sign and returned value. Simple? Yes, theory is simple, but practise is much better. Let’s say and example:

// Standard form
var HelloWorld = function (name) {
  console.log('Hello world from' + name);
}

// Arrow form
var ArrowHello = (name) => console.log('Arrow world from' + name)

As you can see, there is name (but of course, it’s optional), argument – or many arguments, and code to return. Of course, you can use many arguments. You can also create more complicated functions with many operations – you should use braces then:

var Calculate = (value1, value2) => {
  value1 = parseInt(value1)
  value2 = parseInt(value2)
  return value1 * value2 * 3.14
}

Shorter form is one of the most important advantages of arrow functions. But there is second, more important – when we use arrow functions, there is no “separate” this object inside them. Arrow functions always uses this from external scope, so… we can use them in objects, to modify data without binding:

// Standard form
function MyAccount() {
  this.amount = 0

  setInterval(function addMoney() {
    this.amount++ // It will not work for parent amount!
  }, 1000);
}


// Arrow version
function MyAccount() {
  this.amount = 0

  setInterval(() => {
    this.amount++
  }, 1000);
}

This example shows “power” of arrow functions – we don’t have to bind this keyword, just use it from parent scope. It can be very helpful and with that you can avoid some misunderstandings. 

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.