src/content/docs/linter/rules/use-const.mdx
import { Tabs, TabItem } from '@astrojs/starlight/components';
<Tabs> <TabItem label="JavaScript (and super languages)" icon="seti:javascript"> ## Summary - Rule available since: `v1.0.0` - Diagnostic Category: [`lint/style/useConst`](/reference/diagnostics#diagnostic-category) - This rule is **recommended**, meaning it is enabled by default. - This rule has a [**safe**](/linter/#safe-fixes) fix. - The default severity of this rule is [**warning**](/reference/diagnostics#warning). - Sources: - Same as [`prefer-const`](https://eslint.org/docs/latest/rules/prefer-const){
"linter": {
"rules": {
"style": {
"useConst": "error"
}
}
}
}
Require const declarations for variables that are only assigned once.
Variables that are initialized and never reassigned and
variables that are only assigned once can be declared as const.
let a = 3;
console.log(a);
// `a` is redefined (not reassigned) on each loop step.
for (let a of [1, 2, 3]) {
console.log(a);
}
// `a` is redefined (not reassigned) on each loop step.
for (let a in [1, 2, 3]) {
console.log(a);
}
let a;
a = 0;
let a = 3;
{
let a = 4;
a = 2;
}
let a = 2;
a = 3;
console.log(a);
let a = 1, b = 2;
b = 3;
let a;
a; // the variable is read before its assignment
a = 0;
Since v2.2, the rule no longer reports variables that are read in an inner function before being written. This can result in false negatives. For example, the following code is now valid:
let a;
function f() {
return a; // read
}
a = 0; // written