prefer-arrow-callback
Require arrow functions for callbacks
fixable
A function passed as a callback gets its own this, so this.save() inside it only works if you add .bind(this). An arrow function uses the surrounding code's this, and it's shorter.
A callback is left alone if an arrow function can't replace it: a generator, a function that calls itself by name, or one that uses arguments or new.target. By default a callback that uses this without .bind(this) is left alone too.
--fix rewrites the callback as an arrow function and removes .bind(this).
Configure#
Off by default. To turn it on:
bunfig.toml
[lint.rules]
"prefer-arrow-callback" = "error" # or "warn"Every option, set to its default:
bunfig.toml
[lint.rules]
"prefer-arrow-callback" = ["error", {
allowNamedFunctions = false,
allowUnboundThis = true,
}]Examples#
example.js2 problems
const prices = items.map(function (item) {Unexpected function expression.
return item.price;
});
button.addEventListener("click", function () {Unexpected function expression.
this.save();
}.bind(this));example.jsNo problems
const prices = items.map((item) => item.price);
button.addEventListener("click", () => {
this.save();
});
// `this` is the button here. An arrow function would change that.
button.addEventListener("click", function () {
this.classList.add("active");
});
// Calls itself by name
walk(tree, function visit(node) {
node.children.forEach(visit);
});Options#
| Option | Default | What it does |
|---|---|---|
allowNamedFunctions | false | Allow a callback that has a name, which shows up in stack traces. |
allowUnboundThis | true | Allow a callback that uses this without .bind(this). With false it's reported but not fixed. |
example.jswith
{ "allowNamedFunctions": true }No problemsitems.forEach(function logItem(item) {
console.log(item);
});example.jswith
{ "allowUnboundThis": false }1 problembutton.addEventListener("click", function () {Unexpected function expression.
this.classList.add("active");
});