Linter · Rules
func-names
Require or disallow names for function expressions
A callback written as function () {} shows up as <anonymous> in stack traces and profiles. When several callbacks are involved, you can't tell from the trace which one failed.
Arrow functions and methods aren't checked.
Configure
Off by default. To turn it on:
[lint.rules]
"func-names" = "error" # or "warn"
Every option, set to its default. The ones that are commented out are unset by default.
[lint.rules]
"func-names" = [
"error",
"always", # "always", "as-needed" or "never"
{
# generators = <"always", "as-needed" or "never">,
},
]
Examples
Reported:
button.addEventListener("click", function () {
save();
});
export default function () {
return "ready";
}
Not reported:
button.addEventListener("click", function onClick() {
save();
});
button.addEventListener("blur", () => save());
Options
[lint.rules]
func-names = ["error", "as-needed"]
| Option | What it does |
|---|---|
"always" (default) | Every function expression needs a name. |
"as-needed" | A name is only needed where JavaScript doesn't give the function one on its own. |
"never" | No function expression can have a name, unless the function refers to itself by that name. |
A second option, { "generators": "always" | "as-needed" | "never" }, sets the same choice for generator functions only. Without it, generators follow the first option.
"as-needed"
A function that's assigned to a variable or used as the value of an object key takes that name, so it doesn't need its own:
const save = function () {};
const handlers = {
close: function () {},
};
With "always", both are reported:
const save = function () {};
const handlers = {
close: function () {},
};
A callback doesn't get a name that way, and neither does a function assigned to object.property. Both are still reported:
items.forEach(function (item) {
render(item);
});
handlers.open = function () {};
"never"
items.forEach(function renderItem(item) {
render(item);
});
items.forEach(function (item) {
render(item);
});
const factorial = function fact(n) {
return n <= 1 ? 1 : n * fact(n - 1);
};
generators
run(function* () {
yield 1;
});