unicorn/no-array-callback-reference
Disallow passing a function by name to array methods such as `map` and `filter`
map, filter, and the other array methods call their callback with three arguments: the element, its index, and the array. A function that you pass by name receives all three. If it has an optional second parameter, or gets one in a later version of its library, the index ends up there.
The rule checks every, filter, find, findLast, findIndex, findLastIndex, flatMap, forEach, map, some, reduce, and reduceRight.
Configure#
Off by default. To turn it on:
[lint.rules]
"unicorn/no-array-callback-reference" = "error" # or "warn"Examples#
Reported:
const sizes = ["10", "10", "10"].map(parseInt); // [10, NaN, 2]import { formatUser } from "./format.js";
const lines = users.map(formatUser);Not reported:
const sizes = ["10", "10", "10"].map((text) => parseInt(text, 10)); // [10, 10, 10]import { formatUser } from "./format.js";
const lines = users.map((user) => formatUser(user));Built-in constructors such as Boolean, String, and Number are allowed, and so is a function made with .bind():
const present = values.filter(Boolean);
const labels = ids.map(String);
const rows = items.map(table.render.bind(table));The rule can't tell what's an array. It skips calls on a property, such as store.users.map(), and on common library names, such as _, lodash, $, jQuery, React, and Vue:
const lines = store.users.map(formatUser);
const names = _.map(users, formatUser);