prefer-const detect unnecessary let
See original GitHub issuePlease describe what the rule should do: Detect uses of let where reassignments and accesses happen only in the same function, Eg not in a nested function or loop.
If a variable is only reassigned and accessed inside one function, then the value must have stabilized by the point of the function’s return, therefore it can always be replaced with a const. (While this also applies to loops, the developer would have to switch to using reduce or recursion)
What category of rule is this? (place an “X” next to just one item)
[ x] Enforces code style [ ] Warns about a potential error [x ] Suggests an alternate way of doing something [ ] Other (please specify:)
Provide 2-3 code examples that this rule will warn about:
// bad
function foo() {
let itWorks = false;
try {
checkIfItWorks();
// only mutated/accessed inside function foo
itWorks = true;
} catch {
// only mutated/accessed inside function foo
itWorks = false;
}
...
}
// good
function foo() {
const itWorks = (() =>
try {
checkIfItWorks();
return true;
} catch {
return false;
}
})();
...
}
// bad
function foo() {
let result = getResult();
if (!result) {
// only mutated/accessed inside function foo
result = getDefaultResult();
}
...;
}
// good
function foo() {
const result = getResult() || getDefaultResult();
...;
}
// good
function urlUpdater() {
let innerUrl = 'https://example.com';
const DEFAULT = Symbol('DEFAULT');
return function getOrUpdate(newUrl = DEFAULT) {
if (newUrl === DEFAULT) {
return innerUrl;
}
// defined in function foo and mutated in getOrUpdate
innerUrl = newUrl;
}
}
// 'good'
function isPromiseZalgo() {
let canary = true;
// canary accessed in arrow. Changes behavior if using https://github.com/krakenjs/zalgo-promise
const isZalgoProm = Promise.resolve().then(v => canary);
canary = false;
return isZalgoProm;
}
// 'good'
function countIf(vals, fn) {
let count = 0;
for (const val of vals) {
if fn(vals) {
// defined in countIf, mutated in nested for loop.
count = count + 1;
}
}
}
Why should this rule be included in ESLint (instead of a plugin)? Would be a sensible enough to add an option to prefer const.
Issue Analytics
- State:
- Created 6 years ago
- Reactions:3
- Comments:16 (16 by maintainers)
I’m not suggesting an autofixer, I think that would be out of scope. In terms of what I’d prefer for your example, I’d go for:
Could you clarify what the rule would do in cases like this?
At the moment I don’t think this preference is common enough to be worth adding to ESLint core, but I’m open to being convinced otherwise. (Of course, you could always enforce this preference yourself by implementing it as a rule in a plugin.)