This rule raises an issue when code uses object.length - index calculations in methods that support negative indexing, such as
slice(), at(), splice(), and others.
JavaScript provides negative indexing for many array and string methods, which allows accessing elements from the end of a collection using
negative numbers. When you write array.slice(array.length - 2, array.length - 1), you’re doing unnecessary calculations that make the
code harder to read and understand.
Negative indices are more concise and express the intent more clearly. The expression -2 immediately tells you "second from the end",
while array.length - 2 requires mental calculation to understand the same concept.
Using negative indices also reduces the risk of errors. With array.length - index calculations, you might accidentally use the wrong
variable name or make arithmetic mistakes. Negative indices eliminate these potential sources of bugs.
Additionally, negative indices are more performant since they avoid the property access to .length and the subtraction operation,
though this performance difference is typically negligible in practice.
This issue affects code readability and maintainability. While it doesn’t cause runtime errors, it makes code unnecessarily verbose and harder to
understand. The extra .length property accesses and arithmetic operations also add minor performance overhead.
Replace object.length - n with -n in method calls that support negative indexing. This works for methods like
slice(), at(), splice(), and others on arrays, strings, and typed arrays.
const lastTwo = array.slice(array.length - 2); // Noncompliant const lastElement = array.at(array.length - 1); // Noncompliant array.splice(array.length - 1, 1); // Noncompliant
const lastTwo = array.slice(-2); const lastElement = array.at(-1); array.splice(-1, 1);