ES6 Arrow Functions — two benefits

Two significant benefits of using arrow functions are:

  • arrow functions are less verbose than traditional functions
  • arrow functions take the this from their surroundings (lexical binding)

Less verbose

The following simple example highlights the differences between arrow functions and traditional functions in the manner of verbosity:

// arrow function
const sum = (a, b) => (a + b);
// traditional function
const sum = function(a, b) {
  return (a + b);
}

Arrow functions are considered to be short-hands of traditional functions.

Context binding

Unlike traditional functions the arrow functions have this lexical binding: they take the this argument from their surroundings, so you don’t need bind() or const that = this anymore.

// ES5
API.prototype.get = function(resource) {
// `this` inside the `Promise` callback will have another context
// than expected,
// so assigning `this` to a local `that` variable
const that = this;

return new Promise(function(resolve, reject) {
http.get(that.uri + resource, function(data) {
resolve(data);
});
});
};
// ES6
API.prototype.get = function(resource) {
  // `this` has the same context as its surrounding function,
// inside the `Promise` callback
  return new Promise((resolve, reject) => {
http.get(this.uri + resource, function(data) {
resolve(data);
});
});
};

The following variables are all lexical inside arrow functions:

  • arguments
  • super
  • this
  • new.target

Arrow function syntax

Specifying parameters:

() => { ... } // no parameter
x => { ... } // one parameter, an identifier
(x, y) => { ... } // several parameters

Specifying a body:

x => { return x * x }  // block
x => x * x // expression, equivalent to previous line

As a conclusion, arrow functions are less verbose to declare than traditional functions, traditional functions are bad non-method functions because of `this`.

You have to think about some solutions to use the surrounding context inside the traditional function.

Solution 1: assigning the surrounded context to a local variable to use this inside the traditional function e.g. const that = this.

Solution 2: binding the context into the traditional function whenever it is going to be called, e.g. this.handleClick.bind(this)

Solution 3: using ES6 arrow functions.