Use concise functions without changing their meaning
Arrow functions provide a compact expression form and use lexical this from their surrounding context. They do not create their own this or arguments binding and cannot be used as constructors. This makes them useful callbacks, but not interchangeable with every method.
const double = value => value * 2;
const add = (left, right) => left + right;
const makeStudent = name => ({ name, completed: 0 });
console.log(double(6)); // 12
console.log(add(2, 3)); // 5
console.log(makeStudent('Asha').completed); // 0An expression body returns its expression implicitly. A block body needs an explicit return. Parentheses around an object literal distinguish it from a function block.
Lexical this in a callback
const counter = {
value: 0,
increaseLater() {
setTimeout(() => {
this.value += 1;
console.log(this.value);
}, 0);
}
};
counter.increaseLater(); // eventually logs 1The method is a normal method, so this is counter when called as shown. Its nested arrow remembers that this. Replacing the method itself with an arrow would not make this automatically refer to counter.
Scope and readability
Arrow parameters and local variables follow lexical scope rules. A one-line arrow is useful for a short transformation; a long chain of nested arrows is not automatically clearer. Name substantial operations so stack traces and tests explain what failed.
Common mistakes
value => { value * 2; }returns undefined because the block lacks return.- Calling an arrow with new throws because it is not constructible.
- Using an arrow as a DOM listener does not give it the listener's dynamic this; use the event's currentTarget when needed.
Practice
Rewrite double with a block body and explicit return. Then create an object with a normal method that returns its name. Compare it with an arrow property and explain why the surrounding lexical this, not object-literal placement, controls the arrow.