liveBook · Manning

Arrow function

As explained in JavaScript in Depth

A JavaScript function form with lexical this behavior and a restricted set of function capabilities compared with ordinary functions.

A callback can silently lose the object it was meant to update. Arrow functions avoid that failure by capturing this when they are created instead of recalculating it at the call site. section 6.3 section 6.3.3

An arrow is not merely shorter function syntax. It creates a function object without [[Construct]], an own this binding, an arguments object, or a prototype property. Its [[Environment]] supplies the surrounding this value and other captured variables. section 6.1 section 6.2.3

Use arrow functions when their deliberately restricted capabilities match the job:

  • Preserve the surrounding this inside callbacks such as timers or event operations. section 6.2.3 section 6.3.3
  • Do not use an arrow as a constructor: new Arrow() throws because the function lacks [[Construct]]. section 6.1 section 6.2.3
  • Use rest parameters when access to all arguments is required, because arrows provide no arguments object. section 6.2.3

Preserving the object in a delayed callback

const cabinet = { label: 'Main cabinet', identifyBroken: function() { setTimeout(function() { console.log(this.label); }, 100); }, identifyFixed: function() { setTimeout(() => { console.log(this.label); }, 100); } }; The ordinary callback determines this when the timer invokes it; the arrow reuses the cabinet method's this. section 6.3.3 section 6.3

Table 6.1 The four forms of functions create very real differences in behavior
Capability
Declaration
Expression
Arrow
Class
Has [[Construct]]
✓
✓
✗
✓
Has own this binding
✓
✓
✗
✓
Has arguments object
✓
✓
✗
✓
Has prototype property
✓
✓
✗
✓
Hoisted
✓
 
✗
✗
Requires new
✗
✗
N/A
✓

Compare declarations, expressions, arrows, and classes by constructor support, this binding, arguments access, prototype properties, hoisting, and new requirements. section 6.2

How JavaScript in Depth covers it

How deep it goes
Explains internal slots, creation-time this capture, constructor restrictions, and rest-parameter replacement for arguments access.
Examples
Demonstrates delayed cabinet callbacks, failed construction with new, and collecting arguments through a rest parameter.
What it assumes
Assumes familiarity with JavaScript functions and this while reinforcing call-time versus creation-time binding.
What you can do after
Diagnose callback this bugs, choose arrows for lexical binding, and replace missing arguments access with rest parameters.
How it connects
Connects arrow functions to this binding, closures, callbacks, constructors, internal slots, and rest parameters.

Also explained in

Compare how 9 books explain arrow function →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of JavaScript in Depth. The section links point to the parts of the book it draws on.