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 this binding of its own, no arguments object, no prototype property, and it cannot be called with the new keyword. Use an arrow function when you are writing a short callback that does not need a changing this, and avoid it when you need an object method, a constructor, or a prototype method.
// An arrow function with a short body.
const double = (n) => n * 2;
// An arrow function with a longer body.
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 out is that an arrow function has no prototype property, so the new keyword has nothing to build an instance from and it throws a TypeError. That is the same rule that stops you from using an arrow function as a class constructor, or as an event handler that needs the element to be the receiver.
Arrow functions also have no arguments object. Inside an arrow function, the word arguments refers to the arguments object of the enclosing function, or it fails at the top level of a module. If you need the arguments, then use a rest parameter instead.
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. Some style guides even require the braces and the explicit return, so that a missing return cannot slip through without anybody noticing.