no-constant-binary-expression

Disallow comparisons and &&, ||, ?? that always give the same result

error by default

Some expressions look like they depend on a value but always give the same result. a + b ?? c means (a + b) ?? c, and a sum is never null, so c is never used. items === [] is always false, because [] is a new array that isn't equal to anything else.

The rule reports:

  • && and || where the left side is always truthy or always falsy
  • ?? where the left side is never null or undefined, or always is
  • ==, !=, === and !== where the result is always the same

This rule is on by default.

Configure#

On by default as an error. To turn it off:

bunfig.toml
[lint.rules]
"no-constant-binary-expression" = "off" # or "warn"

Every option, set to its default:

bunfig.toml
[lint.rules]
"no-constant-binary-expression" = ["error", {
  checkRelationalComparisons = false,
  allowLiteralToggle = true,
}]

Examples#

example.js3 problems
const label = "Hello, " + user.name ?? "guest";

if (items === []) {
  showEmptyState();
}

const isMissing = !user.email === undefined;
example.jsNo problems
const label = "Hello, " + (user.name ?? "guest");

if (items.length === 0) {
  showEmptyState();
}

const isMissing = user.email === undefined;

Options#

OptionDefaultWhat it does
checkRelationalComparisonsfalseAlso report <, <=, > and >= between two literal values. With an oxlint config, the default is true.
allowLiteralToggletrueAllow true, false, 0 or 1 on the left of && or ||.

false && ... is how people switch a piece of code off for a while, so it's allowed by default. Only bun lint has allowLiteralToggle. With an ESLint config file these are reported, as in ESLint.

example.jsxNo problems
const page = <main>{false && <DebugPanel />}</main>;
example.jsxwith { "allowLiteralToggle": false }1 problem
const page = <main>{false && <DebugPanel />}</main>;
example.jswith { "checkRelationalComparisons": true }1 problem
const isLarge = 1024 > 4096;
example.jsNo problems
const isLarge = 1024 > 4096;