Arrow Functions
Shorter syntax and lexical `this` - plus when arrow functions are the wrong choice.
Arrow functions are a compact function syntax that captures this from the surrounding scope instead of binding it dynamically.
The basic arrow syntax removes the function keyword. Parentheses around a single parameter are optional; a single-expression body can omit braces and return.
// Traditional expression
const double = function (n) {
return n * 2;
};
// Arrow - equivalent
const triple = (n) => n * 3;
// Multi-statement body still needs braces and return
const clamp = (n, min, max) => {
if (n < min) return min;
if (n > max) return max;
return n;
};
console.log(double(5)); // 10
console.log(triple(5)); // 15
console.log(clamp(12, 0, 10)); // 10Arrow functions capture this lexically - from the enclosing scope at definition time, not from the caller. This makes them ideal as callbacks inside methods.
class Timer {
constructor() {
this.seconds = 0;
}
start() {
// Arrow function: `this` is the Timer instance
setInterval(() => {
this.seconds++;
console.log(this.seconds);
}, 1000);
}
}
// With a regular function, `this` would be undefined (strict mode)
// or the global object - the classic setTimeout/setInterval trap.
const t = new Timer();
t.start(); // 1, 2, 3 ...Arrow functions cannot be used as constructors, and they have no arguments object. They also cannot be generator functions.
const Foo = () => {};
// new Foo(); // TypeError: Foo is not a constructor
// Arrow functions have no `arguments` - use rest params instead
const sum = (...nums) => nums.reduce((a, b) => a + b, 0);
console.log(sum(1, 2, 3)); // 6Object method shorthand (or a regular function) is the right choice when the method needs to reference the owning object via this. An arrow method silently captures the wrong this.
const counter = {
count: 0,
// WRONG - arrow captures `this` from module scope, not the object
badIncrement: () => {
counter.count++; // forced to reference by name - fragile
},
// CORRECT - method shorthand binds `this` to the receiver
increment() {
this.count++;
},
};
counter.increment();
console.log(counter.count); // 1In production
Arrow functions cannot be used as object methods when the method needs dynamic this (the owning object), cannot be constructors, and cannot be generators. Use arrow functions for callbacks, array method predicates, and any inner function that should inherit this from the surrounding method. Use the function keyword (or method shorthand) for anything that defines its own this - class methods, Express route handlers that rely on this, and generator functions. Mixing the two up is one of the quietest sources of undefined is not an object errors in production.
Enjoyed this? Get more essays on software craft delivered to your inbox.
Subscribe free