Skip to content
← Back to rules

unicorn/prefer-at Pedantic

⚠️ 🛠 💡 A dangerous auto-fix and a suggestion are available for this rule.

What it does ​

Prefer the Array#at() and String#at() methods for index access.

This rule also discourages using String#charAt(). It also checks String#substring() calls that extract a single character.

Why is this bad? ​

The .at() method is more readable and consistent for accessing elements by index, especially for negative indices which access elements from the end of the array or string.

Examples ​

Examples of incorrect code for this rule:

js
const foo = array[array.length - 1];
const foo = array.slice(-1)[0];
const foo = string.charAt(string.length - 1);

Examples of correct code for this rule:

js
const foo = array.at(-1);
const foo = array.at(-5);
const foo = string.at(-1);

Configuration ​

This rule accepts a configuration object with the following properties:

checkAllIndexAccess ​

type: boolean

default: false

Check all index access, not just special patterns like array.length - 1. When enabled, array[0], array[1], etc. will also be flagged.

getLastElementFunctions ​

type: string[]

default: []

List of function names to treat as "get last element" functions. These functions will be checked for .at(-1) usage.

How to use ​

To enable this rule using the config file or in the CLI, you can use:

json
{
  "rules": {
    "unicorn/prefer-at": "error"
  }
}
ts
import { defineConfig } from "oxlint";

export default defineConfig({
  rules: {
    "unicorn/prefer-at": "error",
  },
});
bash
oxlint --deny unicorn/prefer-at

Version ​

This rule was added in v1.20.0.

References ​