unicorn/no-negated-condition

Disallow a negated condition in an if with an else and in a ternary

fixable

When both branches are written out, a negated condition makes you read "if not this, else that" and turn it around in your head. Test the positive case and swap the branches.

A condition counts as negated if it's !value, a != b, or a !== b.

--fix removes the negation and swaps the two branches.

Configure#

Off by default. To turn it on:

bunfig.toml
[lint.rules]
"unicorn/no-negated-condition" = "error" # or "warn"

Examples#

example.js2 problems
if (!user) {
  showLogin();
} else {
  showProfile(user);
}

const label = count !== 1 ? "items" : "item";
example.jsNo problems
if (user) {
  showProfile(user);
} else {
  showLogin();
}

const label = count === 1 ? "item" : "items";

An if without an else has no branches to swap, and neither does one that continues with else if:

example.jsNo problems
if (!user) {
  showLogin();
}

if (!user) {
  showLogin();
} else if (user.isAdmin) {
  showSettings();
}