DEV Community

Sanjar Afaq
Sanjar Afaq

Posted on

Use positives for conditionals - if, ternary true case, boolean variables

Prefer positive conditionals/checks

In conditionals - like if, ternary, boolean variables, prefer storing/checking positive conditions over equivalent negative ones.

what is positive depends on the goal of the feature.

// example 1
const hasNoEnergy = !getStatus(); // problem: negative stored in boolean

if (hasNoEnergy) {
  injectFuel();
} else {
  changeOrbit();
}

// example 2
const hasEnergy = getStatus();

if (!hasEnergy) { // problem: negative checked in if
  injectFuel();
} else {
  changeOrbit();
}

// these are complicated, need to be read deliberately
Enter fullscreen mode Exit fullscreen mode
// simple, better
const hasEnergy = getStatus();

if (hasEnergy) {
  changeOrbit();
} else {
  injectFuel();
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay