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") {
  showSettings();
}

const title = "" ? "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:

ValueWhat it does
"allExceptWhileTrue" (default)Check loops, but allow while (true).
"all" or trueCheck loops, including while (true).
"none" or falseDon't check loops.
example.jswith { "checkLoops": "all" }1 problem
while (true) {
  poll();
}

The default only allows the literal true in a while:

example.js2 problems
while (1) {
  poll();
}

do {
  poll();
} while (true);
example.jswith { "checkLoops": "none" }No problems
while (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 problems
function* ids() {
  let next = 0;
  while (true) {
    yield next++;
  }
}