📝 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#at() for index access and String#charAt().
This rule complements unicorn/prefer-string-slice. This rule handles supported one-character substring() patterns, while unicorn/prefer-string-slice handles general string slicing.
// ❌
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 = string.substring(index, index + 1);
// ✅
const foo = string.at(index);// ✅
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;// ✅
// Common DOM collection patterns like `.children`, `.childNodes`, and `querySelectorAll()` are ignored because they are not guaranteed to support `.at()`.
const foo = element.children[element.children.length - 1];This means non-DOM objects with those exact property or method names are also ignored.
// ✅
// This rule intentionally ignores `arguments`, which is array-like but does not have `Array#at()`.
function foo() {
return arguments[arguments.length - 1];
}Type: object
Type: boolean
Default: false
This rule only checks negative indexes by default, but you can also check non-negative integer 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);/* eslint unicorn/prefer-at: ["error", {"getLastElementFunctions": ["utils.lastElement"]}] */
// ✅
const foo = bar.at(-1);