r/badcode • sadistic • Apr 22 '21

js ternary operators at their maximum potential

Post image
960 Upvotes

73 comments sorted by

166

u/Koala_King_ Apr 22 '21

Couldn’t you just do cmd.run || cmd.fire || cmd.execute || cmd.callback ? I’m not super familiar with js. Worked with it a bit, but still not great, so please correct me if I’m wrong.

94

u/DizzySkin Apr 22 '21

Nowadays you could also use the null coalesce operator ?? which would be preferable to || since logical or can be confused by false. For example, if cmd.fire is false, the result of || would be cmd.callback, the result of ?? would be cmd.fire.

20

u/Koala_King_ Apr 22 '21

That’s true, but in this case where you are seemingly wanting to save a function reference to call later, || would probably be the preferred method, seeing as you would be more likely to find an actual function, rather than a Boolean value. Otherwise later on it might equate to calling false(). Just my thoughts. Again, I’m not super familiar with js. My day job is mobile apps in Flutter/Dart.

14

u/Not_Sugden Apr 22 '21

?? would be better in this case if its expected to be a funftion or undefined/null, a function or false is a weird type to use, function or undefined / null makes more sense

4

u/Koala_King_ Apr 23 '21

The typing might make more sense, but if there happens to be a point where it isn’t the typing you expect, wouldn’t || help correct for that and make sure it comes back to the correct type?

9

u/recycle4science Apr 23 '21

If you've got false where you expect a function reference, you'd want to find out about it sooner rather than later. When you try execute run() and the browser complains that false isn't a function, that may be easier to debug than simply, "why is the wrong function running?"

7

u/Koala_King_ Apr 23 '21

That’s fair. I suppose I’m looking at it like “all these functions are equivalent, but might be given different names in different areas of the code because we’ve had 5 developers in the past 2 years”

2

u/Tvde1 Apr 23 '21

If you are putting wrong types in variables you have bigger things to worry about than || vs ??. You should get help and use a type safe language.

4

u/recycle4science Apr 23 '21

As much as I like type safety, everyone doesn't have the luxury to e.g. rebuild a massive legacy application in typescript.

2

u/Tvde1 Apr 23 '21

Typescript isn't type safe

1

u/recycle4science Apr 23 '21 edited Apr 23 '21

It's the closest thing the frontend has got, and this is a javascript conversation.

Edit: to be fair, javascript runs on servers too. Substitute Haskell for typescript in my previous comment if you like.

→ More replies (0)

3

u/guccidumbass Apr 23 '21

both || and ?? seem like a wrong answer to me - if you want the first callable thing, but a nonempty string is supplied, and you call that, you get a TypeError

imo, the best possible solution for this problem is [cmd.run, cmd.fire, cmd.execute, cmd.callback].find(x => typeof x === 'function') || null

or, to avoid edge cases like that, just use typescript. it's 2021, if it's a new project then there is no reason not to

10

u/Major_Fudgemuffin Apr 23 '21 edited Apr 23 '21

Yep that would work. JavaScript (and many others) implement what's called Short Circuit Conditionals or Lazy Evaluation, which is a fancy way of saying that if you're checking for multiple things inside an If statement (or just checking for condition in general) if the first check makes the statement true it won't bother checking the rest.

So once cmd.run gets executed, it'll skip the remaining ones. But if cmd.run can't be found, it moves onto trying cmd.fire instead.

Edit: added simpler name

9

u/[deleted] Apr 23 '21

Don't worry, anyone who's a decent developer would know what you mean by short circuit.

1

u/4sent4 Apr 23 '21

But functions are not executed here. This codes finds first function to not evaluate to false

-20

u/TigreDeLosLlanos Apr 23 '21

Lazy evaluation. Why give it a fucked up name when there is already a correct term for it?

It's when they introduce a feature to a JS framework and give it a fancy name, then talk about it like it's the essential part you've got to understand only that it's some kind of basic concept you already watched several times.

14

u/[deleted] Apr 23 '21

The fuck are you on? I've heard about "short-circuiting" two decades ago when I was learning C++ in high school. I thought 'lazy evaluation' was the later terminology but regardless it never bothered me either way.

7

u/Major_Fudgemuffin Apr 23 '21

Same. And as long as you and your team are on the same terms, who cares what you call it?

4

u/Major_Fudgemuffin Apr 23 '21

Thanks for the second term. Always down for helping more people understand what I'm talking about.

3

u/ws-ilazki &{$$_[0]}(@{$$_[1]}); Apr 23 '21

Something to be aware of is that short circuiting is specific to conditional evaluation, while lazy evaluation is a general strategy for deferring expression evaluation until needed. Lazy evaluation is the counterpart to eager or "strict" evaluation, which is how most languages behave.

Most languages (Haskell being a notable exception) use eager evaluation by default, though you can usually introduce laziness in some way, often by wrapping your expression in a function call so that it evaluation only happens at the time of calling. Laziness lets you do things like introduce infinite data structures by evaluating a function to determine the next element of a list so that you only take what you need instead of trying to compute the entire sequence.

So the person correcting you is partly right (short-circuit evaluation is a form of laziness), but also kind of wrong (lazy evaluation is a lot more). You were correct to call it short-circuit evaluation in this context and only got corrected because that guy was just trying to be an "I am very smart" pedantic jackass and failed at it.

1

u/Major_Fudgemuffin Apr 23 '21

Hey thanks for the info! That's about what I've learned as well (thought I didn't know the Haskell details!) but I've found it's not really worth arguing with people, especially online (as tempting as it can be).

I find that combating the toxicity on this sub (and this site at a whole, really) with some manners and positivity to be my way of being the change I want to see.

2

u/ws-ilazki &{$$_[0]}(@{$$_[1]}); Apr 24 '21

I understand and mostly agree, at least with regard to not getting into pointless arguments with people. However, ignoring or placating someone to avoid confrontation because they chose to wrap their wrongness in belligerent aggression can give the impression that they're right and you accepted the correction.

I dislike that because it leads to a spread of misinformation, so while I'll avoid prolonged arguments I'm still going to call out BS where I see it. If the person wants to have a civil discussion from there I'll go with it; if not I say my piece and move on because life's too short to waste on pointless fights.

1

u/Major_Fudgemuffin Apr 24 '21

Oh I agree. Just didn't seem like a point worth arguing about.

I respect that though.

0

u/[deleted] Apr 22 '21

[deleted]

21

u/[deleted] Apr 22 '21

it's pretty common to do that in JS, but now we've got ??

10

u/Quiet_Newt6119 Apr 22 '21

Null coalescing only applies the right hand side operand when the leftmost one is either null or undefined, as opposed to any falsy value with the or operator. '' || true would return true, but '' ?? true would return ''

-1

u/TigreDeLosLlanos Apr 23 '21

What's pretty common in JS is weird elsewhere. At least the || operator is present anywhere, but those people don't use it too much because they know how to code properly.

8

u/blehmann1 depraved Apr 22 '21

I don't think anyone gets scared by logical or, it's one of the first things you learn in any language.

Now, for beginners boolean variables can be confusing, which is why you see a lot of if(foo == true), although in JavaScript the similar if(foo === true) is sometimes necessary and not redundant. But I highly doubt anyone would find this use of || more confusing than this ternary soup, even if they are a beginner.

2

u/Sp1um Jun 09 '21

Not a JS dev, not sure if the reduce signature is correct

['run', 'fire', 'execute', 'callback'].reduce(null, (acc, k) => acc || cmd[k])

2

u/SpeckyYT sadistic Jun 09 '21

I don't think anyone would ever come on this idea, but that works quite well.

.reduce takes as first parameter the function, so you shouldn't add the null.

2

u/Sp1um Jun 09 '21

The null is supposed to be the accumulator initial value

2

u/SpeckyYT sadistic Jun 10 '21

The accumulator's initial value can be optionally set as the second parameter.

43

u/-IoI- Apr 22 '21

My boss hates me using ternary operators - I can see why now.

46

u/EnigmaticHam Apr 23 '21

Ternary statements have a legitimate use - when you have one test condition and always have two branches in your code. But when you've got more than one, just use if else.

1

u/recycle4science Apr 23 '21

Or reconsider your architecture lol

14

u/[deleted] Apr 23 '21

[removed] — view removed comment

0

u/recycle4science Apr 23 '21

Lol fair enough. I didn't really register what exactly you were saying, I was talking about more like what the op posted.

22

u/ws-ilazki &{$$_[0]}(@{$$_[1]}); Apr 23 '21

There's really nothing wrong with ternary operators as a concept, they're just if expressions instead of statements, meaning they're just conditionals that return a value. In fact, some languages like OCaml and F# only have if expressions and it works out quite well, though it helps that they can use if/then/else instead of ? and :, which is more readable IMO.

The real problem is people thinking writing idiotic one-liners is "clever", resulting in unreadable garbage. If they did the same thing but wrote it as a one-line chain of if (foo) { foo } else if (bar) { bar } else baz it would be just as awful, no ternary operators needed. Similarly, if you added line breaks and indentation the ternary usage wouldn't be quite as bad to read. Like this:

cmd.run
? cmd.run 
: cmd.fire 
  ? cmd.fire 
  : cmd.execute 
    ? cmd.execute 
    : cmd.callback 
      ? cmd.callback 
      : null

The code still sucks, but at least with breaks and indentation I can actually follow the chain of conditionals.

Sometimes it's the language's fault and it should be blamed for having bad features or poor design, but other times (like this) it really is the programmer's fault and we shouldn't be excusing their mistakes by acting like the language made them do it.

6

u/christian-mann Apr 23 '21

I would probably write that as

cmd.run ? cmd.run :
cmd.fire ? cmd.fire

Et cetera. But there are better ways, like the null-coalesce operator, metaprogramming tricks, or fixing your architecture so you know what kind of object you're getting.

2

u/ws-ilazki &{$$_[0]}(@{$$_[1]}); Apr 23 '21

I agree, there are definitely better ways to write the code instead of if/else chaining in any form, which is why I said the code still sucks. It's just not the operator's fault, you can split it up and make it readable just fine. I also agree that the example I used for formatting it across multiple lines isn't necessarily ideal (and isn't even what I'd use normally). I just wrote it that way trying to show the similarity to nesting if/else statements when spread out across lines for readability. If I were writing that kind of chained conditional expression for real it would end up similar to what you did, with a slight difference:

foo ? "foo"
: bar ? "bar"
: baz ? "baz"
: "lol"

It helps show that the following lines are part of the expression, plus I read ? as then and : as else, so writing it that way makes it read similarly to how these sorts of expressions usually get written in languages like OCaml and F# (though you don't see it as often because pattern matching is amazing):

if foo then "foo"
else if bar then "bar"
else if baz then "baz"
else "lol"

I wish more languages treated if/else keywords as expressions because it's nicer and more consistent than conditional statements. Using ?: instead works but I'm not a fan of abusing symbols to do the same job because the keywords got hijacked for statements. Still, that's not reason enough to demonise the use of conditional expressions just because some people want to abuse them for terrible one-liners.

4

u/Nilstrieb Apr 23 '21

The real problem is that many languages thought that control flow statements are a good idea.

2

u/ws-ilazki &{$$_[0]}(@{$$_[1]}); Apr 23 '21

Exactly! Having control flow as statements just forces those languages to either not have control flow expressions or to abuse symbols to reimplement the same control flow as expressions. Which doesn't make sense because you could get the same result with an expression just by ignoring the return value.

I've found I prefer languages where everything is an expression because it gives you more flexibility and power while also being more consistent.

2

u/TheAJGman Apr 23 '21

I use them a lot for things like return this if flag else None. Don't think simple ones impact readability.

1

u/amanj41 Apr 23 '21

Ternary operators are fine and concise in some instances... but I haaaate when devs chain them like this. It’s uncommon enough I always have to reason about the result

44

u/MurdoMaclachlan public boolean isInt(int i) { return true; } Apr 22 '21

Image Transcription: Code


const cmdJson = {
    type: cmd.type || 4,
    run: cmd.run ? cmd.run : cmd.fire ? cmd.fire : cmd.execute ? cmd.execute : cmd.callback ? cmd.callback : null
}

I'm a human volunteer content transcriber for Reddit and you could be too! If you'd like more information on what we do and why we do it, click here!

26

u/blehmann1 depraved Apr 22 '21

good human

10

u/UszeTaham Apr 22 '21

Ah yes, poor man's pattern matching

2

u/recycle4science Apr 23 '21

Needs more newlines!

13

u/Rawrplus depraved Apr 22 '21

Screw the logical or ||

5

u/Major_Fudgemuffin Apr 23 '21

I asked a coworker to make a change in their PR just yesterday because they had a single level of this (ternary operator feeding into another) on a single line.

OP this picture is my nightmare.

7

u/INTO_NIGHT Apr 22 '21

I thought the rule for ternary was have only two things compared not even sure what this would return

23

u/fukitol- Apr 22 '21

The else clause of every ternary operator here is another ternary operator. It'd work, but everyone would hate you and make fun of you for this.

6

u/CrepuscularSoul Apr 22 '21

Basically yeah. I love ternary for simple one line if else stuff, I might let a second nested one slide if it's formatted for readability, but beyond that I'm not approving that PR.

8

u/HattyJetty Apr 22 '21

That's why ternary operators are right-associative in most languages. Unlike... ahem... php

3

u/Paul_Robert_ Apr 23 '21

Laughs in Haskell

3

u/[deleted] Apr 23 '21

reminds me of when i was contributing to a project and the tech lead literally told me

If you can write a multi-line thing in a single line, that's better ;)

in my experience, 90% of good maintainable software dev is writing code that takes as little mental overhead for humans to understand.

span multiple lines, tell a story that's very easy to understand. oh and...

DOCBLOCK YA CODE

4

u/EnigmaticHam Apr 23 '21

If you have multiple cases, just use if-else instead of being "clever" by smashing everything into one line.

2

u/mothibault Apr 22 '21

Now I wanna see the nested try catch equivalent 😂

2

u/ososalsosal Apr 23 '21

Honestly there was a niche video processing language based in very esrly JavaScript where the ONLY way to do conditions was ternaries, so that produced some... uh, pretty eye-pleasing code

1

u/fugogugo Apr 23 '21

what does that || 4 does?

3

u/skrtpowbetch Apr 23 '21 edited Apr 23 '21

i might be wrong but i think what that says is the value assigned to type would be cmd.type if it’s truth-y, else 4. not completely sure though

edit: “type” will equal cmd.type if cmd.type is defined, else 4

4

u/fforde_thinking Apr 23 '21

You were right the first time. If cmd.type == false then it will set "type" to 4

1

u/killersquirel11 Apr 23 '21

This isn't even their maximum potential. I did a group project and discovered a file where my teammate chained 25 ternary statements together (this was in Verilog)

1

u/[deleted] Apr 23 '21

It's like jackass. I bet you can't do it in one line, Greg!

1

u/gohanshouldgetUI Apr 23 '21

That's surprisingly not too hard to read

1

u/[deleted] Apr 23 '21

1

u/[deleted] Apr 23 '21

2much4myBrain

0

u/[deleted] Apr 23 '21

[deleted]

1

u/SpeckyYT sadistic Apr 23 '21

Using || would be good enough