π Prefer .at() method for index access and String#charAt().
πΌ 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);