ES6 Basics Part 3 – Arrow Functions

ES6 can be thought of as a new version of Javascript. Currently most JS is ES5.

Over the next few articles, I’m going to break down the new features & syntax of ES6 into bite-size chunks. Please note that some experience writing JS is required to make full uses of these articles.

This is part 3 of many so please keep checking back for the next article in the series.
Part 1 – const & let can be found here.
Part 2 – Template Strings can be found here.

Part 4 – Classes can be found here.

Currently, to declare a function in JS you would do this:

const multiply  = function(a, b){
 return a * b;
};

 

With ES6 the function keyword is no longer needed. It is replaced with a fat arrow => after the argument list.

const multiply  = (a, b) => {
 return a * b;
};

 

It is possible to reduce the syntax even further. In functions that only have a single JS expression, it is possible to remove the curley braces & drop the return keyword. This creates an implicit return – just a way of saying automatically return.

const multiply  = (a, b) =>  a * b;

 

In functions with a single argument, you can also drop the parentheses around it.

const tripple  = a => 3 * a;

Where a function has no arguments you need the parentheses.

Why & How?

It can reduce code clutter, making function declarations shorter & easier to read. There is also another benefit. Look at the code below and see if you can spot the issue.

const cars = {
 models: ['s1', 's3', 's4', 's5', 's6', 's7', 's8'],
 manufacturer: 'Audi',
 carSummary: function() {
  return this.models.map(function(model) {
   return `The ${model} is a car made by ${this.manufacturer}`;
  });
 }
};

This code will throw an error – this.manufacturer will not work as the function is being passed off to somewhere else, so the value of this is lost. This could be solved by using bind, but Arrow Functions can help with this issue.

By making use of the fat arrow function below, the code below will now work because it is using Lexical This.

const cars = {
 models: ['s1', 's3', 's4', 's5', 's6', 's7', 's8'],
 manufacturer: 'Audi',
 carSummary: function() {
  return this.models.map((model) => {
   return `The ${model} is a car made by ${this.manufacturer}`;
  });
 }
};

This means that the placement of the this keyword influences how it is evaluated. When it is placed inside a fat arrow function, it is set to the same value as what it would mean in the surrounding code. In the example above,  this = team.

 

Check back shortly for the part 4– ES6 Classes.

 

As not all browsers support ES6 code yet, Babel should be used to transpile (convert) the code into ES5 code.

Comments