💼 This rule is enabled in the following configs: ✅ recommended, ☑️ unopinionated.
🔧💡 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.slice(-1)[0];
// ❌
const foo = array.slice(-1).pop();
// ❌
const foo = array.slice(-1).shift();
// ❌
const foo = lodash.last(array);
// ✅
const foo = array.at(-1);// ❌
const foo = array[array.length - 5];
// ✅
const foo = array.at(-5);// ❌
const foo = string.charAt(string.length - 5);
// ✅
const foo = string.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); // FailsType: 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);