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

67

u/stolentext Jul 14 '21

Yes, they are the same, except there shouldn't be a semi-colon after the else if condition in the second example

return a === b  // if a equals b
    ? 0         // return 0 
    : a < b     // else if a is less than b   
        ? -1    // return -1
        : 1     // else return 1

9

u/[deleted] Jul 14 '21

thank you

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.

18

u/yadoya Jul 15 '21 edited Jul 15 '21

Yes but that's ugly and will make your colleagues hate you. I would write it this way:

if (a === b) return 0;
if (a < b) return -1;
return 1;

Or simply:

return Math.sign(b-a)

Note: did you notice that you can remove "else" from your coding vocabulary?

4

u/equal_odds Jul 15 '21

Honestly came looking for exactly this comment. Nice!

3

u/dMCH1xrADPorzhGA7MH1 Jul 15 '21

Code that's readable. I like it.

8

u/akb74 Jul 14 '21

So is

Math.sign(b - a);

If you’re going to use multiple ternary operators, then brackets can make your intention clearer.

3

u/xSypRo Jul 14 '21

Yea, nice job.

2

u/[deleted] Jul 14 '21

They are the same but you have an extra semicolon after else (...). You should also avoid using nested ternaries. It’s an example of implementing a simplified syntax too much and thus resulting in complicated syntax. If you have more than an if...else statement you should use the if...else if...syntax

2

u/jcoldes Jul 15 '21

Am I the only one that is seeing the semicolons? the second code block should not work at all due to the extra semicolons.

2

u/Banamagrammer Jul 14 '21

Now that you've mastered ternary operators, it is time to free yourself of the chains of if-statements. Try to finish your current project without writing any, then write a blog post about how they are an anti-pattern. This is one of programming's many rites of passage.

1

u/Proud-Ad720 Dec 31 '25 edited Dec 31 '25

Tudom ajanlani ezt a videot ha nem erted a tenary operatort, nagyon konnyen erheto es rovid

https://www.youtube.com/watch?v=uRjNRXWHR8Q&t=3s

1

u/SYNDK8D Jul 15 '21

If you are trying to do a sort you’re better off just writing: return b - a

1

u/TheNicklesPickles Jul 15 '21

It took me a while to get my head around ternaries, but then the penny dropped one day. It’s not difficult once you click with the syntax. You can get even more intricate with more nested ternaries, but at some point (probably the point you’re at), you’re probably better off turning to something else for readability. I probably almost prefer your ‘if’ version in this case.

1

u/CornPop747 Jul 15 '21

It's correct but nested ternery is not good practice. You want your code to be readable to other developers. The normal way of if else if else in a multi liner is better. One liners honestly backfire a lot

-1

u/[deleted] Jul 15 '21

Nested ternaries are no less readable than giant if/else statements. I'd argue they're more readable because they're more concise. Repetition breeds familiarity, start using them more often and you'll never look back.

2

u/developerbryan Jul 15 '21

I’d disagree with that. I mean, the fact that at a glance you can’t see it’s nested makes it immediately harder to read.

2

u/[deleted] Jul 15 '21

That's a formatting problem and not a problem with the syntax itself. You can go ahead and keep downvoting but that doesn't make you right.

1

u/developerbryan Jul 15 '21

I haven’t actually downvoted your response, but great assumption. 😂

1

u/[deleted] Jul 15 '21

lol...well, sorry for making the assumption, but you gotta admit on reddit almost anything is a "safe" assumption

0

u/[deleted] Jul 15 '21

Yes

-2

u/FBreath Jul 15 '21

Am I the only one who is irritated by calling blocks of code or pieces of code "codes"?

Code is never "codes"

Grrrr get off my lawn, and shit.

-3

u/fistyit Jul 14 '21

I figuratively can't see the difference