This rule raises an issue when code uses verbose patterns like array[array.length - 1], array.slice(-1)[0], or
string.charAt(string.length - 1) to access elements by index.
JavaScript provides the .at() method as a modern, cleaner way to access array and string elements by index. This method is especially
useful for negative indexing, where you want to access elements from the end.
Older patterns like array[array.length - 1] or array.slice(-1)[0] are verbose and harder to read. They also have
performance implications - methods like slice() create new arrays, which uses extra memory and processing time.
The .at() method accepts both positive and negative indices. Negative indices count from the end, so array.at(-1) gets
the last element, array.at(-2) gets the second-to-last, and so on. This makes the code more expressive and easier to understand.
Using .at() also provides consistency across different JavaScript objects - it works the same way on arrays, strings, typed arrays,
NodeLists, and other array-like objects.
Using outdated index access patterns makes code harder to read and maintain. Methods like slice() create unnecessary intermediate
arrays, which can impact performance in loops or frequently called functions. The verbose syntax also increases the chance of off-by-one errors when
calculating indices.
Replace array[array.length - n] with array.at(-n) for cleaner negative indexing.
const lastElement = array[array.length - 1]; // Noncompliant const fifthFromEnd = array[array.length - 5]; // Noncompliant
const lastElement = array.at(-1); const fifthFromEnd = array.at(-5);