Arrow function

2 snippets in JavaScript

Also written as arrow function this

JSJavaScript

Arrow Functions

JS · Functions
Syntax
const fn = (params) => expression;
const fn = (params) => { ... };
Example
const double = n => n * 2;
console.log(double(7)); // 14

const greet = (name, greeting = "Hello") => `${greeting}, ${name}!`;
console.log(greet("Ava")); // "Hello, Ava!"

// Return an object literal (wrap in parentheses)
const makeUser = (name, id) => ({ name, id });
console.log(makeUser("Bo", 1));

Note Arrow functions have no own this, arguments, or super. They inherit this from the surrounding scope, making them unsuitable as object methods or constructors.

Losing 'this' Context

JS · Common Mistakes
Syntax
// Problem: extracting a method loses its 'this'
// Fix: use bind(), arrow function, or keep method call
Example
class Timer {
  count = 0;

  // BUG: 'this' is undefined in the callback
  startBroken() {
    setInterval(function () {
      this.count++; // TypeError!
    }, 1000);
  }

  // FIX 1: arrow function inherits 'this'
  startFixed() {
    setInterval(() => {
      this.count++;
      console.log(this.count);
    }, 1000);
  }
}

// FIX 2: bind the method
const timer = new Timer();
const increment = timer.startFixed.bind(timer);

Note Arrow functions, .bind(), or storing this in a variable (const self = this) all solve this. Arrow functions are the cleanest modern solution.

Frequently asked questions

How does JavaScript handle arrow function?
JavaScript covers this with 2 copy-ready snippets on this page. The "Arrow Functions" snippet in JavaScript uses `const fn = (params) => expression;`.
Which code does the JavaScript example use?
The "Arrow Functions" snippet uses `const fn = (params) => expression;`, from the Functions section of the JavaScript cheat sheet.
What other JavaScript snippets are shown for "arrow function"?
Besides "Arrow Functions", this page also shows "Losing 'this' Context".
Is there anything to watch out for?
Yes. For "Arrow Functions": Arrow functions have no own this, arguments, or super. They inherit this from the surrounding scope, making them unsuitable as object methods or constructors.