atAccesses
Prefer using .at() for accessing elements at negative indices.
✅ This rule is included in the tsstylisticandstylisticStrictpresets.
Accessing an element at the end of an array or string using array[array.length - 1] is less readable than using the .at() method with a negative index.
The .at() method provides a cleaner syntax for accessing elements from the end of a sequence.
Examples
Section titled “Examples”const const last: number
last = const array: number[]
array[const array: number[]
array.Array<number>.length: number
Gets or sets the length of the array. This is a number one higher than the highest index in the array.
length - 1];const const secondLast: string
secondLast = const items: string[]
items[const items: string[]
items.Array<string>.length: number
Gets or sets the length of the array. This is a number one higher than the highest index in the array.
length - 2];const const lastChar: string
lastChar = const text: string
text[const text: string
text.String.length: number
Returns the length of a String object.
length - 1];const const last: number | undefined
last = const array: number[]
array.Array<number>.at(index: number): number | undefined
Returns the item located at the specified index.
at(-1);const const secondLast: string | undefined
secondLast = const items: string[]
items.Array<string>.at(index: number): string | undefined
Returns the item located at the specified index.
at(-2);const const lastChar: string | undefined
lastChar = const text: string
text.String.at(index: number): string | undefined
Returns a new String consisting of the single UTF-16 code unit located at the specified index.
at(-1);const const first: number
first = const array: number[]
array[0];const const element: number
element = const array: number[]
array[const dynamicIndex: number
dynamicIndex];Options
Section titled “Options”This rule is not configurable.
When Not To Use It
Section titled “When Not To Use It”If you need to support environments that do not have the .at() method (pre-ES2022), or if your project has a polyfill that only covers certain cases, you can disable this rule.
Further Reading
Section titled “Further Reading”Equivalents in Other Linters
Section titled “Equivalents in Other Linters”- Biome:
useAtIndex - ESLint:
unicorn/prefer-at