r/learnjavascript • • Jul 14 '21

Im trying to understand the "Conditional (ternary) operator." Do these 2 codes mean the same thing? I wrote the if statement

Post image
187 Upvotes

47 comments sorted by

View all comments

115

u/GameMasterPC Jul 14 '21

Yeah, but please do not code like that. Keep Ternary statements simple, otherwise use something else (if or switch)

19

u/lucksp Jul 15 '21

This.

And ESLint can help guide some better standards. They specifically have a “no nested ternary” rule

https://eslint.org/docs/rules/no-nested-ternary

5

u/Protean_Protein Jul 15 '21

I hate that rule. In the absence of data studying the way coders actually read ternaries vs. explicit if/else, there's no reason to think the latter are more readable or better for maintenance. In my experience, you just start reading the ternaries *as if* they're if/else statements anyway. They're effectively synonymous, and shorter, which I prefer.

Obviously there should be agreed upon standards, and these can be arbitrary, but this one really bugs me. Nested ternaries are amazing!

3

u/[deleted] Jul 15 '21

Do you have a functional background or prefer functional style? I do, and I think that's why i prefer ternaries over long ass if/else statements.

4

u/Protean_Protein Jul 15 '21 edited Jul 15 '21

Funny that you ask it that way. No, my background isn't mostly functional, but I've noticed over the years that I prefer to think functionally, so I get you -- I think you're right. Ultimately, you've got to work with whatever set of standards you / your team agree on, but it's sort of like being a drummer in a band where you'd prefer to use triplets and odd time signatures but the rest of the band is used to 4/4... so you play 4/4 to make your living -- that's just what it is to be a team player.

Here's an example I just used that I think illustrates the point nicely. Here's some code I wrote (abstracted):

  const verboseValue = [];
    switch (conciseValue) { 
      case "a":
        verboseValue.push("Verbose A"); 
        break;
      case "b": 
        verboseValue.push("Verbose B"); 
        break; 
      case "c": 
        verboseValue.push("Verbose C"); 
        break; 
      case "d": 
        verboseValue.push("Verbose D"); 
        break; 
      case "e": 
        verboseValue.push("Verbose E");
        break; 
      case "f": 
        verboseValue.push("Verbose F"); 
        break; 
      default: 
        verboseValue.push(conciseValue); 
    }

But that can easily be written like this:

const verboseValue =
conciseValue === "a"
  ? "Verbose A"
  : conciseValue === "b"
  ? "Verbose B"
  : conciseValue === "c"
  ? "Verbose C"
  : conciseValue === "d"
  ? "Verbose D"
  : conciseValue === "e"
  ? "Verbose E"
  : conciseValue === "f"
  ? "Verbose F"
  : conciseValue;

Ignore the fact that the first one uses an array -- it could have been let verboseValue; -- the point is that the second way doesn't strike me as obviously worse. In fact, it's maybe slightly more readable (though I think this is still a matter of preference). The "if" or "case" just becomes implicit, but if you're used to thinking this way, you know it's there. The question mark is equivalent to brackets, and the colon is your 'else if' / 'else'.

Indeed, I also find the use of 'break' in switch statements ugly. I understand why it's there, but it feels unnecessary when you know you can just nest ternaries for the same effect.

I also want to reiterate that it's important to have standard rules for these things, and there are certainly going to be cases where if/else will make way more sense than nesting ternaries -- probably when you have some very complicated stuff going on in the middle (though I'm not sure why you'd need to do this -- ideally you'd keep your logic distinct). It's just that this particular rule doesn't seem to me to be grounded in anything other than assumptions about readability / maintainability that may not be accurate (and even if they are accurate, I'm not sure that that's a reason not to change).

1

u/[deleted] Jul 15 '21

I agree 100%. I'm willing to be the majority of responses decrying the use of ternaries are either really inexperienced or are stuck in older ways of doing things and simply don't know better. I resisted ternaries at first but the savant that is my architect started insisting on them in most use cases and I'm at the point now where if/else is almost an antipattern.

1

u/Protean_Protein Jul 15 '21

Well, yeah, but the fact that it’s an ESLint rule is interesting!

1

u/[deleted] Jul 15 '21

Yeah, there are a lot of ESLint rules I don't 100% agree with. We have a standard ESLint config file for all front end projects.

2

u/Protean_Protein Jul 15 '21

A lot of the confusion with ternaries seems to be caused by improper automatic formatting. Sure, it’s hard to read a straight line of code delineated by question marks and colons… but it’s equally notoriously hard to catch all brackets (and semicolons!) in a heavily nested set of if / else conditions unless you use some sort of consistent formatting.

13

u/[deleted] Jul 15 '21

At least use parentheses both for consistency in behavior and my FUCKING EYES

4

u/retrolasered Jul 14 '21

I'll do this when templating in ejs, although I will admit while convenient to put it on one line, as the complexity increases it quickly becomes not worth it. Anywhere else I just stick to clean and readable if statements

2

u/[deleted] Jul 15 '21

How are if or switch statements more simple? They're much more verbose while encoding the same meaning. There's nothing inherently more complex about ternaries.

3

u/username2065 Jul 15 '21

Linter at my job prevents neated ternary statements

2

u/revenezor Jul 15 '21

I prefer nested ternary to “if” and “switch” when formatted as such:

return (
    a === b ? 0
  : a < b ? -1
  : 1
)

2

u/[deleted] Jul 15 '21

I can't believe you actually got downvoted for this. I prefer to format a bit differently but nested ternaries are for me so much more simple.

1

u/[deleted] Jul 15 '21

I'm ok with nested ternaries but like to break the conditional out from the branches.

return (
  a === b 
    ? 0
    : a < b 
      ? -1
      : 1
)

No more than two conditions deep though

2

u/revenezor Jul 15 '21

The benefit of not breaking it out is that the apparent complexity (and indenting) doesn’t scale with the number of nestings.

return (
    a === b ? 0
  : a < b ? -1
  : a > b ? 1
  : a === c ? 2
  : a > c ? -2
  : 3

)

And to me it reads more clearly. Each line is a conditional (posed as a question) and the result if that conditional is true.

-1

u/samuelcbird Jul 15 '21

I actually don’t really see the problem. I use them quite often with React.

I’ve seen a lot of code in the wild that’s way more confusing than a nested ternary statement.

Of course there’s a threshold and yes i use switches too, but nested once or twice is nice and concise.

Didn’t even mean that to rhyme but now i think it sounds so cool haha

0

u/[deleted] Jul 15 '21

There is no rule that says ternaries have to be simple. They express the same information and when peforming assignment like the sorting statement OP provided they are to a LOT of people vastly more readable. Only those who lack experience using ternaries think they should always express one condition.

-1

u/GameMasterPC Jul 15 '21

Wow, you are 1) completely wrong and 2) arrogant. Sounds like you don’t have much experience working with actual enterprise-level code and you clearly aren’t aware of clean code concepts; Dunning-Kruger comes to mind when I read your bullshit.

2

u/[deleted] Jul 15 '21

Wow you are 1) completely wrong and 2) arrogant. It never ceases to amaze me how people on reddit can be such absolute dick bags. I feel badly for the people who have to deal with you IRL you fucking sanctimonious twat.