ESLint InterlaceESLint Interlace
Plugin: modernizationRules

prefer-at

ESLint rule documentation for prefer-at

📡 Live from GitHub — This documentation is fetched directly from prefer-at.md and cached for 6 hours.

Keywords: Array.at(), negative index, last element, ESLint rule, ES2022, auto-fix, LLM-optimized

Prefer using Array.at() for accessing elements, especially with negative indices

Prefer using Array.at() for accessing elements, especially with negative indices. This rule is part of eslint-plugin-modernization.

Quick Summary

AspectDetails
SeverityWarning (modern JavaScript)
Auto-Fix✅ Yes (converts to .at())
CategoryModernization
ESLint MCP✅ Optimized for ESLint MCP integration
Best ForES2022+ codebases, cleaner array access

Rule Details

Array.at() provides a cleaner way to access array elements, especially the last element or elements from the end.

Why This Matters

IssueImpactSolution
📖 Readabilityarr[arr.length - 1] is verboseUse arr.at(-1)
🐛 Off-by-one errorsEasy to make mistakesNegative indices
🔄 ConsistencyMultiple patterns in codebaseStandardize on .at()

Examples

❌ Incorrect

// Accessing last element
const last = array[array.length - 1];

// Second to last
const secondLast = array[array.length - 2];

// Dynamic negative access
const item = array[array.length - offset];

✅ Correct

// Clean last element access
const last = array.at(-1);

// Second to last
const secondLast = array.at(-2);

// Dynamic negative access
const item = array.at(-offset);

// Also works with strings
const lastChar = string.at(-1);

Configuration Examples

Basic Usage

{
  rules: {
    'architecture/prefer-at': 'warn'
  }
}

Further Reading

Known False Negatives

The following patterns are not detected due to static analysis limitations:

Dynamic Variable References

Why: Static analysis cannot trace values stored in variables or passed through function parameters.

// ❌ NOT DETECTED - Value from variable
const value = externalSource();
processValue(value); // Variable origin not tracked

Mitigation: Implement runtime validation and review code manually. Consider using TypeScript branded types for validated inputs.

Imported Values

Why: When values come from imports, the rule cannot analyze their origin or construction.

// ❌ NOT DETECTED - Value from import
import { getValue } from './helpers';
processValue(getValue()); // Cross-file not tracked

Mitigation: Ensure imported values follow the same constraints. Use TypeScript for type safety.

On this page

No Headings