Skip to content

negativeIndexLengthMethods

Prefer negative index over .length - index for at, 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).

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);

This rule is not configurable.

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.

Made with ❤️‍🔥 in Boston by Josh Goldberg and contributors.