Using Arrow Functions in JavaScript Classes

Updated: March 11, 2023 By: Wolf Post a comment

This article is using arrow functions in a class in modern JavaScript (ES6 and later).

Overview

Arrow functions are a compact and concise way to write function expressions in modern JavaScript. It’s possible to use them in JavaScript classes. However, they have some semantic differences and limitations that you should be aware of. Below are some DOs and DON’Ts for using arrow functions in JavaScript classes:

  • DO use arrow functions for simple one-line methods that don’t need to access this, arguments, or super.
  • DON’T use arrow functions for methods that need to access this, arguments, or super, as they will inherit them from the outer scope instead of the class instance.
  • DON’T use arrow functions for constructors, as they cannot be invoked with the new operator and will throw an error.
  • DON’T use arrow functions for prototype methods, as they will not be added to the prototype chain and will not be inherited by subclasses.
  • DON’T use arrow functions for getters and setters, as they will not work with the get and set keywords.

If you are unsure, the simplest and safest way is to use traditional functions instead of arrow functions (arrow functions are very rare in classes in open-source code bases).

Examples

Correct Use of Arrow Functions in a Class

The code:

class Person {
  constructor(name) {
    this.name = name;
  }

  // This is an arrow function
  sayGoodbye = () => {
    console.log(`Goodbye, I'm ${this.name}`);
  };
}

let person = new Person('Sling Academy');
person.sayGoodbye();

Output:

Goodbye, I'm Sling Academy

This example is correct because our arrow function does not need to access this, arguments, or super, and it is not used as a constructor, a prototype method, or a getter/setter.

Incorrect Use of Arrow Functions in a Class

The code:

// This is wrong
const Person = (name, age) => {
  this.name = name;
  this.age = age;
};

// This will throw an error
let john = new Person('Wolf', 99);

When running the code above, you will end up with this error:

Uncaught TypeError: Person is not a constructor

The reason is that you use an arrow function as a constructor function.

Afterword

The attraction and temptation for using arrow functions is undeniable, but they are not always the best choice, especially when object-oriented programming is involved.