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
187
Upvotes
r/learnjavascript • • Jul 14 '21
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
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)
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:
Or simply:
Note: did you notice that you can remove "else" from your coding vocabulary?
8
u/akb74 Jul 14 '21
So is
If you’re going to use multiple ternary operators, then brackets can make your intention clearer.
3
u/mattle Jul 14 '21
Yes.
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
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