JavaScript ES6 Arrow Functions


This past June, the TC39 committee released the ECMAScript 6 version of JavaScript. It was the biggest upgrade to the language since 1999 when version 3.0 was release. As aside, the committee cancelled the 4.0 version  due to lack of agreement and the 5.0 release was really a 3.1 release, as there really nothing major that came out the version.

One of my favorite features in this release is the arrow function. It’s basically syntactical sugar for writing functions in JavaScript.

Compare the following two similar functions:

That’s nice. I just chopped off the “function”, “return” and the “{}”. I believe they took this from CoffeeScript, but if you are familiar with C# you will recognize this as also being very similar to “lambda expressions”.

Here are some points to keep in mind when using arrow functions.

  • You can have a single line or a multiple line arrow function.
  • In a single line arrow function the braces are optional, but required for a multi-line arrow function.
  • If you have braces then the return statement is required to return something.
  • If only one parameter is provided the parentheses surrounding that parameter is optional.
  • The “this” object retains its reference to the parent function and not the object.

For the last point consider the following code:

The above code throws an error because “this” refers to the global scope because the “setTimeout” function is a part of the global scope. Typically getting around this issue requires you defining a variable that gets the value of “this” at the beginning of the parent function. Another, probably better, approach is to use the bind() function.

Now let’s look at the same code with an arrow function.

Arrow functions preserve the “this” property to its parent function even if the inner closure function was instigated by a function in the global scope.

This makes the code more predictable and easier to reason about and hopefully resolves one of the biggest “gotchas!” in JavaScript.

Stay tuned as I hope to write about more ES6 enhancements.


Leave a Reply

Skip to toolbar