JavaScript Arrow Function Gotchas

ES6, JavaScript,
Illustration: Hachibu

Illustration: Hachibu


Arrow functions are a newish [1] way to write anonymous functions [2] in JavaScript. They differ from function declarations in 2 important ways: syntax and scoping. It’s useful to understand the subtleties because they can break or alter the behavior of your code.

function() {} // old
() => {}      // new

Syntax Gotchas

Arrow functions can be written in several ways whereas function declarations can only be written in 2 ways: named or anonymous.

  1. An Arrow function with curly brackets requires an explicit return. Use this form for multi-line functions.

    x => { return x }
  2. An Arrow function without curly brackets will implicitly return. Use this form for one-line functions.

    x => x
  3. To return an object in an Arrow function without curly brackets, wrap it in parentheses.

    x => ({ x })
  4. An Arrow function with more than one parameter requires parenthesis.

    (x, y) => [x, y]

Scoping Gotchas

Arrow functions and function declarations are practically interchangeable except when it comes to scoping. Arrow functions do not have their own this. They inherit this from their surroundings.

Without Arrow functions we would have to store a reference to this and use that inside of the callback function.

 1var component = {
 2  state: {
 3    counter: 0
 4  },
 5  handleClick() {
 6    var that = this;
 8    setTimeout(function() {
 9      // inner this !== outer this
10      that.state.counter += 1;
11    });
12  }

With Arrow functions we don’t need to store a reference to this because they will inherit this from the outer scope.

 1var component = {
 2  state: {
 3    counter: 0
 4  },
 5  handleClick() {
 6    setTimeout(() => {
 7      // inner this === outer this
 8      this.state.counter += 1;
 9    });
10  }


If you’d like to learn more about Arrow functions I recommend reading ES6 In Depth: Arrow functions.

  1. Arrow functions were introduced in ECMAScript 2015 along with classes and template strings.
  2. Anonymous functions come from Lambda calculus which was created by Alonzo Church in the 1930s.

Thanks to Michael Geraci and MarĂ­n Alcaraz for editing.
If you liked this post, you might also like 7 Ways to Loop in JavaScript or Homage to Sol LeWitt.