When should you use an arrow function, and when should you avoid one?
An arrow function is a shorter syntax with a smaller feature set. It has no own this binding, no own arguments object, no prototype property and it cannot be called with the new keyword. Use one when you are writing a short callback that does not need a dynamic this, and avoid it when you need an object method, a constructor or a prototype method.
// Arrow: expression body, no own this, no own arguments.
const double = (n) => n * 2;
const doubleLong = (n) => {
return n * 2;
};
console.log(double(4)); // 8
console.log(doubleLong(4)); // 8
// A regular function can be used as a constructor.
function Point(x, y) {
this.x = x;
this.y = y;
}
const point = new Point(1, 2);
console.log(point.x, point.y); // 1 2
try {
new (() => {})();
} catch (err) {
console.log("new arrow:", err.name); // "TypeError"
}The other difference that catches people is that an arrow function has no prototype property, so the new keyword has nothing to build an instance from and throws a TypeError. That is the same rule that stops you using an arrow function as a class constructor or as an event handler that relies on the element being the receiver.
Arrow functions also have no arguments object. Inside an arrow, the word arguments refers to the enclosing function's arguments object, or fails in a module top-level context. If you need the arguments, use a rest parameter.
There is a readability point as well. The single-expression form is shorter, but for anything longer than a couple of lines a regular function with a block body is clearer, and some style guides require braces and an explicit return so that a missing return cannot slip through.