no-constant-condition
Disallow conditions that are always truthy or always falsy
warn by default
If a condition never changes, one branch always runs and the other is dead code. It's often a mistake. For example, role === "admin" || "owner" is always truthy, because "owner" is a non-empty string.
The rule checks the test of if, ? :, while, do...while and for. while (true) is allowed by default.
This rule is on by default.
Configure#
On by default as a warning. To turn it off:
bunfig.toml
[lint.rules]
"no-constant-condition" = "off" # or "error"Every option, set to its default:
bunfig.toml
[lint.rules]
"no-constant-condition" = ["warn", {
# "all", "allExceptWhileTrue", "none", true or false
checkLoops = "allExceptWhileTrue",
}]Examples#
example.js2 problems
if (role === "admin" || "owner"Unexpected constant condition.) {
showSettings();
}
const title = ""Unexpected constant condition. ? "Draft" : "Published";example.jsNo problems
if (role === "admin" || role === "owner") {
showSettings();
}
while (true) {
const job = queue.shift();
if (!job) break;
run(job);
}Options#
checkLoops controls how loops are checked:
| Value | What it does |
|---|---|
"allExceptWhileTrue" (default) | Check loops, but allow while (true). |
"all" or true | Check loops, including while (true). |
"none" or false | Don't check loops. |
example.jswith
{ "checkLoops": "all" }1 problemwhile (trueUnexpected constant condition.) {
poll();
}The default only allows the literal true in a while:
example.js2 problems
while (1Unexpected constant condition.) {
poll();
}
do {
poll();
} while (trueUnexpected constant condition.);example.jswith
{ "checkLoops": "none" }No problemswhile (1) {
poll();
}A loop in a generator function isn't reported if it contains a yield, because the caller decides when to stop:
example.jswith
{ "checkLoops": "all" }No problemsfunction* ids() {
let next = 0;
while (true) {
yield next++;
}
}