src/content/docs/linter/rules/use-at-index.mdx
import { Tabs, TabItem } from '@astrojs/starlight/components';
<Tabs> <TabItem label="JavaScript (and super languages)" icon="seti:javascript"> ## Summary - Rule available since: `v1.9.4` - Diagnostic Category: [`lint/style/useAtIndex`](/reference/diagnostics#diagnostic-category) - This rule isn't recommended, so you need to enable it. - This rule has an [**unsafe**](/linter/#unsafe-fixes) fix. - The default severity of this rule is [**information**](/reference/diagnostics#information). - Sources: - Inspired from [`unicorn/prefer-at`](https://github.com/sindresorhus/eslint-plugin-unicorn/blob/main/docs/rules/prefer-at.md) - Same as [`e18e/prefer-array-at`](https://github.com/e18e/eslint-plugin){
"linter": {
"rules": {
"style": {
"useAtIndex": "error"
}
}
}
}
Use at() instead of integer index access.
Accessing an element at the end of an array or a string is inconvenient because you have to subtract the length of the array or the string from the backward 1-based index of the element to access.
For example, to access the last element of an array or a string, you would have to write array[array.length - 1].
A more convenient way to achieve the same thing is to use the at() method with a negative index.
To access the last element of an array or a string just write array.at(-1).
This rule enforces the usage of at() over index access, charAt(), and slice()[0] when at() is more convenient.
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 = array.at(-1);
const foo = array.at(-5);
const foo = array[100];
const foo = array.at(array.length - 1);
array[array.length - 1] = foo;