r/badcode • sadistic • Apr 22 '21

js ternary operators at their maximum potential

Post image
960 Upvotes

73 comments sorted by

View all comments

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?"

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)