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.