Skip to content
← Back to rules

eslint/prefer-const Style

🛠️ An auto-fix is available for this rule for some violations.

What it does ​

Requires const declarations for variables that are never reassigned after their initial declaration.

Ignored Files ​

This rule ignores .svelte and .vue files entirely. Oxlint only parses the <script> blocks of these files, so a binding that the template reassigns looks like it is never reassigned, and turning it into a const makes the framework compiler fail. In Svelte the template writes through bind:this={el} and bind:value={x}; in Vue a <script setup> let is a setup-let binding that v-model="x" and inline handlers such as @click="x = 1" assign to directly.

Why is this bad? ​

If a variable is never reassigned, using the const declaration is better. const declaration tells readers, "this variable is never reassigned," reducing cognitive load and improving maintainability.

Examples ​

Examples of incorrect code for this rule:

js
let a = 3;
console.log(a);

let b;
b = 0;
console.log(b);

for (let i in [1, 2, 3]) {
  console.log(i);
}

Examples of correct code for this rule:

js
const a = 0;

let a;
a = 0;
a = 1;

let a;
if (true) {
  a = 0;
}

for (const i in [1, 2, 3]) {
  console.log(i);
}

Configuration ​

destructuring ​

type: "any" | "all"

Configures how destructuring assignments are handled.

"any" ​

Warn if any of the variables in a destructuring assignment should be const.

"all" ​

Only warn if all variables in a destructuring assignment should be const. Otherwise, ignore them.

ignoreReadBeforeAssign ​

type: boolean

default: false

If true, the rule will not report variables that are read before their initial assignment. This is mainly useful for preventing conflicts with the typescript/no-use-before-define rule.

How to use ​

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

json
{
  "rules": {
    "prefer-const": "error"
  }
}
ts
import { defineConfig } from "oxlint";

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

Version ​

This rule was added in v1.43.0.

References ​