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
| Aspect | Details |
|---|---|
| Severity | Warning (modern JavaScript) |
| Auto-Fix | ✅ Yes (converts to .at()) |
| Category | Modernization |
| ESLint MCP | ✅ Optimized for ESLint MCP integration |
| Best For | ES2022+ 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
| Issue | Impact | Solution |
|---|---|---|
| 📖 Readability | arr[arr.length - 1] is verbose | Use arr.at(-1) |
| 🐛 Off-by-one errors | Easy to make mistakes | Negative indices |
| 🔄 Consistency | Multiple patterns in codebase | Standardize 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'
}
}Related Rules
prefer-node-protocol- Modern Node.js imports
Further Reading
- Array.at() - MDN - MDN reference
- ES2022 Features - ECMAScript specification
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 trackedMitigation: 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 trackedMitigation: Ensure imported values follow the same constraints. Use TypeScript for type safety.