DEV Community

danielpdev
danielpdev

Posted on

2 1

Easy refactor ternary conditions to if else

Have you ever had a pain on understanding ternary conditions put in the code by others colleagues that have left the project?

Well, if you think understanding a simple ternary it's easy for you, look at the following example:


const [a1, a2, a3] = [true, 3, true];

const a4 = 0;
const [a5, a6, a7] = [false, 2, false];

const result = a1 ? a4 : a2 ? a4 : a5 ? a6 : a7 ? a4 :
  a5 ? a6 : a7 ? a4 : a5 ? a6 : a7 ? a4 : a5 ? a6 : a7;

console.log(result);

What will be the value of result?
Take your time....
.............
...........
.........
.......
.....
...
..
.
R: 0

Now imagine that we have a lot more expressions and not just numbers and booleans. Yeah, not the best day of changing something in the old codebase.

But there is a package that auto refactors to an IIFE(Immediately Invoked Function Expression) easy and more readable.

Its a babel plugin wrote a while ago

Now, after using ternary to if else we get:

var a = function () {
  if (a1) {
    return a4;
  }

  return function () {
    if (a2) {
      return a4;
    }

    return function () {
      if (a5) {
        return a6;
      }

      return function () {
        if (a7) {
          return a4;
        }

        return function () {
          if (a5) {
            return a6;
          }

          return function () {
            if (a7) {
              return a4;
            }

            return function () {
              if (a5) {
                return a6;
              }

              return function () {
                if (a7) {
                  return a4;
                }

                return function () {
                  if (a5) {
                    return a6;
                  }

                  return a7;
                }();
              }();
            }();
          }();
        }();
      }();
    }();
  }();
}();

Enjoy and keep on coding!

👋 One new thing before you go

Tired of getting nickel-and-dimed on your software career? 😒

We have created a membership program that helps cap your costs so you can build and experiment for less. And we currently have early-bird pricing which makes it an even better value! 🐥

Just one of many great perks of being part of the network ❤️

Top comments (4)

Collapse
 
savagepixie profile image
SavagePixie • Edited

The ternary could have been more readable if each part of the expression had its own line, but other than that, it's not particularly difficult to read: is thus truthy? Then do this, else is the next element truthy? Then do this, else...

I honestly fail to see how a function with so many nested returns is more readable. I could see a case for a bunch of else if statements, if one is not used to reading ternaries. But this function within a function within a function just seems more complicated to read to me.

Collapse
 
danielpdev profile image
danielpdev

For me, converting the ternary expression to a function within a function was far more readable.
I had multiple condition for every nested ternary expression and it was hell.

Think about if you have to add some code for one of the nested conditions, for me it's just more easier to have it like that.

It's also not mandatory to leave it like that, I find it easy to refactor the function and not a nested ternary that is on the same line.

Collapse
 
moopet profile image
Ben Sinclair

The "before" code made me raise my eyebrows, because I can't imagine anyone creating anything like that by hand. It's the sort of thing that would come out of a code minifier, not out of a human brain.

Then I looked at the "after" code and I think it's worse.

This is a great example of where splitting it up into nicer variable names and keeping each if separate would be better:


let bestCarnivalRide = null;

if (mySistersHeight > 172) {
  bestCarnivalRide = 'rollercoaster';

if (mySistersFears.indexOf('spiders') > -1) {
  bestCarnivalRide ='house-of-horrors';
}

// etc.
Collapse
 
danielpdev profile image
danielpdev

The code provided was just an example and not real code in production.

The real problem I had was with a nested ternary written in a string and then passed to eval. It had a real long nested conditions and babel plugin helped me refactored that code.

I agree with you, no code like that should be in a production application.

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Dive into an ocean of knowledge with this thought-provoking post, revered deeply within the supportive DEV Community. Developers of all levels are welcome to join and enhance our collective intelligence.

Saying a simple "thank you" can brighten someone's day. Share your gratitude in the comments below!

On DEV, sharing ideas eases our path and fortifies our community connections. Found this helpful? Sending a quick thanks to the author can be profoundly valued.

Okay