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 nevernullorundefined, 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.nameUnexpected constant nullishness on the left-hand side of a ?? expression. ?? "guest";
if (items === []Unexpected comparison to newly constructed object. These two values can never be equal.) {
showEmptyState();
}
const isMissing = !user.emailUnexpected constant binary expression. Compares constantly with the right-hand side of the ===. === undefined;example.jsNo problems
const label = "Hello, " + (user.name ?? "guest");
if (items.length === 0) {
showEmptyState();
}
const isMissing = user.email === undefined;Options#
| Option | Default | What it does |
|---|---|---|
checkRelationalComparisons | false | Also report <, <=, > and >= between two literal values. With an oxlint config, the default is true. |
allowLiteralToggle | true | Allow 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 problemconst page = <main>{falseUnexpected constant truthiness on the left-hand side of a && expression. && <DebugPanel />}</main>;example.jswith
{ "checkRelationalComparisons": true }1 problemconst isLarge = 1024 > 4096Unexpected constant relational comparison. Both sides of the > are literal values.;example.jsNo problems
const isLarge = 1024 > 4096;