liveBook · Manning

Arrow function

As explained in Secrets of the JavaScript Ninja, Second Edition

A concise JavaScript function syntax that captures this lexically from its creation context rather than creating its own binding.

A callback can be short yet still do useful work. An arrow function defines a function value with less syntax than a function expression: `(a, b) => a - b` drops the `function` keyword and, for a single expression, the braces and `return`. It is an ES6 feature, so check browser compatibility when supporting older browsers. section 3.3.2

Read the shape from left to right:

  • Put parameters before `=>`. One parameter can omit parentheses; zero or multiple parameters need them. section 3.3.2
  • Use an expression for a concise returned value, as in `name => "Greetings " + name`. For several statements, use braces and an explicit `return` when a result is needed. section 3.3.2

A shorter sort callback

`values.sort((value1, value2) => value1 - value2)` replaces a function expression that returns the same difference. The arrow changes how the callback is written, not why the array calls it. section 3.3.2

The more important difference appears in callbacks involving `this`. An arrow function has no `this` of its own: it retains the value from where it was defined. A click handler created inside a constructor can therefore update the constructed object even when the browser invokes the handler. section 4.3.1

Listing 4.13. Using arrow functions to work around callback function contexts
<button id="test">Click Me!</button>                             #A
<script>
  function Button(){                                             #B
    this.clicked = false;
    this.click = () => {                                         #C
      this.clicked = true;
      assert(button.clicked,"The button has been clicked");//    #D
    };
  }
  var button = new Button(); 
  var elem = document.getElementById("test");                    #E
  elem.addEventListener("click", button.click);                  #E
</script>

Follow where the click handler is created, then where it is registered. Its `this.clicked` update targets the constructed object. section 4.3.1

Watch where the arrow is created, not just where it is stored. In the shown browser example, an arrow placed in an object literal in global code retains global `this`; clicking updates `window.clicked`, not the object’s `clicked` property. An object literal alone does not give its arrow the object as `this`. section 4.3.1

Listing 4.14. Arrow functions and object literals
<button id="test">Click Me!</button>
<script>
  assert(this === window, "this === window");                        #A
  var button = {                                                     #B
    clicked: false,
    click: () => {                                                   #C
      this.clicked = true;
      assert(button.clicked,"The button has been clicked");          #D
      assert(this === window, "In arrow function this === window");  #E
      assert(window.clicked, "clicked is stored in window");         #F
    }
  }
  
  var elem = document.getElementById("test");
  elem.addEventListener("click", button.click);
</script>

Compare the assertions for the object and `window` to see the misplaced click state. section 4.3.1

How Secrets of the JavaScript Ninja, Second Edition covers it

How deep it goes
Works through parameter and body forms plus lexical `this` in callbacks, while leaving browser-compatibility details to a linked resource.
Examples
Compares array-sort and greeting functions, then contrasts constructor and object-literal click handlers.
What it assumes
Assumes some JavaScript function and browser-callback familiarity while introducing arrow syntax and its `this` behavior.
What you can do after
Diagnose/debug with it when a browser click callback changes the wrong object's state.
How it connects
Connects function expressions and first-class functions to callbacks, `this` binding, constructors, object literals, and event listeners.

Also explained in

Compare how 7 books explain arrow function →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Secrets of the JavaScript Ninja, Second Edition. The section links point to the parts of the book it draws on.