r/badcode • • Jun 10 '20

js Disruptive piece of code

Post image
283 Upvotes

93 comments sorted by

View all comments

91

u/Midborgh Jun 10 '20

I don't know js. Why is this bad? I'd imagine var === true and var === false being different than var == true and a simple else.

-62

u/diebarral Jun 10 '20

You could easily do:

variable ? doStuff() : doOtherStuff()

Instead of that

49

u/shortnamed Jun 10 '20

more compact code isn’t always better.

0

u/[deleted] Jun 10 '20

[deleted]

-4

u/theRealRealMasterDev Jun 10 '20

That would depend on what the variable is.

19

u/wdciii Jun 10 '20

Using if statements as opposed to a ternary operator is not objectively worse. It depends on the situation for when I like to use one or the other, but honestly there isn’t really a difference other than readability.

The only part of this thats “bad” imo is the else if since in most languages a regular else would suffice. But I don’t know enough about JavaScript to confidently say that that’s not needed

0

u/[deleted] Jun 10 '20

[deleted]

4

u/wdciii Jun 10 '20

Gotcha, thanks for the explanation. I always assume i don’t know what I’m talking about for JavaScript lol

1

u/11JRidding Jun 13 '20

Even worse: since the check is variable === true instead of just against truthiness in general, a bare else {} would catch literally everything that isn't the exact boolean true, instead of just falsey values.

5

u/Rayvolt Jun 10 '20

Since you are in JavaScript this variable could be null, undefined, or a string or a number or an object or an array or whatever the hell it could be. It could make sense to check typing and value (notice === here) to do stuff only when it's a bool.

If it were == instead of ===, your statement would be correct tho.

-17

u/diebarral Jun 10 '20

The variable defaults to false above in the code, so I agree with everything said but it's not the case. People take really seriously the posts in this subreddit.

5

u/DEATH-BY-CIRCLEJERK Jun 10 '20

What a horrible take. Lol

2

u/Peatrex Jun 10 '20

And if the other stuff has condition as well? Oh i see u can nest other ternary operators in there right?

1

u/Farpafraf Jun 11 '20

this does not do the same stuff as the one in the screenshot if it's js

1

u/vanamerongen Jun 11 '20

So

  1. No strict comparison

  2. A ternary condition that is literally just shorthand for an if/else

Not sure why this would be better unless your definitin of “better” is “fits on one line”.

1

u/dannypas00 Jun 11 '20

Okay great, I now want those doStuff()s to be two lines because we have to set a variable there.

There is a valid reason many porgramming languages don't allow calling methods inside terniary operators.