ES6 Arrow Functions Explained

By Jordan Pinski On July 3, 2018
  • ES6
  • |
  • JS

Arrow functions are a new feature in ES6 (EcmaScript 6). They make reading & writing JavaScript easier in two ways; allowing for a shorter function syntax, & maintaining the value of ‘this’. 


Shorter Function Syntax

Anonymous functions are used all of the time in JavaScript. One of the most common uses are in addEventListener() calls as the callback function. The ES5 approach to adding an anonymous callback function is this:

btn.addEventListener('click', function(event) {

The anonymous function is the green text. This can now be simplified by using an arrow function like this:

btn.addEventListener('click', event => console.log(event));;

The syntax for arrow functions is as follows: (parameters) => { //do something }.

 If there are more than one parameters being passed to the function they need to be wrapped with parentheses. If there are no parameters being passed you’ll need to use a set of empty parentheses (). Curly brackets are only necessary if multiple lines are needed inside of the function call.


Binding ‘this’

In ES5 every function expression defined it’s own value for this. To retain the value of this in ES5 you need to use the bind method. The bind method works by binding the current value of this to a function so that its value is the same outside as it is inside.

Arrow function expressions don’t define their own value for this, they use the surrounding context to define its value.

Leave a comment

Your email address will not be published. Required fields are marked *