This page looks best with JavaScript enabled

Should you use ternary operator?

 ·   ·  ☕ 2 min read

Yes.
Now, go back to work.. may be?

What the heck is this?

I am sure you used something called if/else?

const sum = a + b;
let result;

if (sum > 100)
  result = "too high";
else
  result = "just right";

Instead of the “elaborate” syntax, we can just shorthand it.

const result = a + b > 100 ? "too high" : "just right";

So, should you use it?

Emm.. it depends.

Ternary operators can get confusing and unreadable for anything more complex than a simple if/else. (yes, that is ‘complex’ and ‘simple’ used innovatively)

const sum = a + b;
let result;

if (sum > 100) {
  result = "too high";
  scaleBackFuture();
}
else if (sum < 100)
  result = "low";
else
  result = "just right";

Translated to..

const result = a + b > 100 ? "too high" : (a + b < 100 ? "low" : "just right");

You may also want to split ‘if’ statement for the sake of sanity, and ternary’s role may become, well, tertiary.

const sum = a + b;
let result;

if (sum >= 100 && (lotteryWon() || (lastSalary > 1000 && today <= withinFirstWeek()))) {
  result = "who cares?";
  splurgeMore();
}
else if (sum == 100)
  result = "low";
else
  result = "just right";
Stay in touch!
Share on

Prashanth Krishnamurthy
WRITTEN BY
Prashanth Krishnamurthy
Technologist | Creator of Things