negativeIndexLengthMethods
Prefer negative index over
.length - indexforat,slice,splice, and similar methods.
✅ This rule is included in the ts stylisticStrict presets.
Array methods like .at(), .slice(), and .splice() accept negative indices to access elements from the end of an array or string.
Using array.slice(array.length - 2) is less readable than array.slice(-2).
Examples
Section titled “Examples”const values = [1, 2, 3];values.slice(values.length - 2);const values = [1, 2, 3];values.slice(values.length - 2, values.length - 1);const values = [1, 2, 3];values.at(values.length - 1);const values = [1, 2, 3];values.splice(values.length - 1, 1);const values = [1, 2, 3];values.with(values.length - 1, 99);const values = [1, 2, 3];Array.prototype.slice.call(values, values.length - 2);const values = [1, 2, 3];values.slice(-2);const values = [1, 2, 3];values.slice(-2, -1);const values = [1, 2, 3];values.at(-1);const values = [1, 2, 3];values.splice(-1, 1);const values = [1, 2, 3];values.with(-1, 99);const values = [1, 2, 3];Array.prototype.slice.call(values, -2);const values = [1, 2, 3];values.slice(1, 2);Options
Section titled “Options”This rule is not configurable.
When Not To Use It
Section titled “When Not To Use It”If you prefer explicit .length - index calculations for documentation purposes, or if you have a codebase convention that requires them for readability in certain contexts, you may want to disable this rule.
Further Reading
Section titled “Further Reading”- MDN: Array.prototype.at()
- MDN: Array.prototype.slice()
- MDN: Array.prototype.splice()
- MDN: Array.prototype.with()
Equivalents in Other Linters
Section titled “Equivalents in Other Linters”- ESLint:
unicorn/prefer-negative-index
Made with ❤️🔥 in Boston by
Josh Goldberg and contributors.