prefer-const
eslint
Safe autofix
eslint.config.js
export default [
{
rules: {
"prefer-const": "error",
},
},
];Require const declarations for variables that are never reassigned after declared
// it's initialized and never reassigned.
let a = 3;
console.log(a);
let b;
b = 0;
console.log(b);
class C {
static {
let a;
a = 0;
console.log(a);
}
}
// `i` is redefined (not reassigned) on each loop step.
for (let i in [1, 2, 3]) {
console.log(i);
}
// `a` is redefined (not reassigned) on each loop step.
for (let a of [1, 2, 3]) {
console.log(a);
}// using const.
const a = 0;
// it's never initialized.
let b;
console.log(b);
// it's reassigned after initialized.
let c;
c = 0;
c = 1;
console.log(c);
// it's initialized in a different block from the declaration.
let d;
if (true) {
d = 0;
}
console.log(d);
// it's initialized in a different scope.
let e;
class C {
#x;
static {
e = obj => obj.#x;
}
}
// it's initialized at a place that we cannot write a variable declaration.
let f;
if (true) f = 0;
// …Examples from the ESLint documentation.
prefer-const
eslint
export default [
{
rules: {
"prefer-const": "error",
},
},
];prefer-const
eslint plugin · style
{
"rules": {
"prefer-const": "error"
}
}style/useConst
style · since 1.0.0
{
"linter": {
"rules": {
"style": {
"useConst": "error"
}
}
}
}Disallow calling some Object.prototype methods directly on objects
Disallow lexical declarations in case clauses
Require rest parameters instead of arguments
Disallow duplicate arguments in function definitions
Disallow variable assignments when the value is not used