🚫 This rule is disabled in the ✅ recommended
config.
🔧💡 This rule is automatically fixable by the --fix
CLI option and manually fixable by editor suggestions.
Prefer Array#at()
, String#at()
, and {TypedArray,NodeList,CSSRuleList,…}#at()
for index access and String#charAt()
.
const foo = array[array.length - 1];
const foo = array[array.length - 5];
const foo = array.slice(-1)[0];
const foo = array.slice(-1).pop();
const foo = array.slice(-5).shift();
const foo = string.charAt(string.length - 5);
const foo = lodash.last(array);
const foo = array.at(-1);
const foo = array.at(-5);
const foo = array[100];
// This rule is not checking this case, but `unicorn/prefer-negative-index` rule will fix it.
const foo = array.at(array.length - 1);
array[array.length - 1] = foo;
Type: object
Type: boolean
Default: false
This rule only check negative indexes by default, but you can also check positive indexes by setting checkAllIndexAccess
to true
.
Example:
{
'unicorn/prefer-at': [
'error',
{
checkAllIndexAccess: true
}
]
}
// eslint unicorn/prefer-at: ["error", {"checkAllIndexAccess": true}]
const foo = bar[10]; // Fails, will fix to `bar.at(10)`
const foo = bar[unknownProperty]; // Passes
const foo = string.charAt(unknownIndex); // Fails
Type: string[]
You can also check custom functions that get last element of objects.
_.last()
, lodash.last()
, and underscore.last()
are always checked.
Example:
{
'unicorn/prefer-at': [
'error',
{
getLastElementFunctions: [
'getLast',
'utils.lastElement'
]
}
]
}
// eslint unicorn/prefer-at: ["error", {"getLastElementFunctions": ["utils.lastElement"]}]
const foo = utils.lastElement(bar); // Fails