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)