ES6 Features: Arrow Functions

ES6 introduces a concept borrowed from other programming languages, like C#, Java, and CoffeeScript, called arrow functions. An arrow function is a way to write shorthand syntax for anonymous functions, all the while keeping the same binding of “this” as the current object .

Let’s start with an example. Say you have an array that you want to iterate through and print the number to the console if x % 2 == 0. Otherwise, you’ll print the title of your widget. This is how you might do it with ES5 or below:

In ES6, you can write this with arrow functions, without the need to bind to the current object.

Advantages of arrow functions:

  1. No need to write function() as the arrow acts as a shorthand
  2. No need to bind the arrow function to the current context of “this.” It does it automatically.TL;DR: Less code = win!

Want to try it out today? The latest Firefox implements most of the arrow functions spec, as does BabelJS, which I will cover separately in another blog post. Go ahead, give it a shot in the FF developer console! And as always, check the compatibility of ES6 features here: