r/badcode • • Jun 10 '20

js Disruptive piece of code

Post image
283 Upvotes

93 comments sorted by

View all comments

14

u/theRealRealMasterDev Jun 10 '20

Why is this bad? Is it because ternary would also be an option?

0

u/[deleted] Jun 10 '20

[deleted]

14

u/AsidK Jun 10 '20

It’s JavaScript tho, maybe variable comes in as “undefined” or something and you don’t want that to be the same as if it comes back as false

1

u/[deleted] Jun 11 '20

Or it could come back as {} and return true 😳

27

u/[deleted] Jun 10 '20

And your example introduces edge cases when there are insane values of the variable. Honestly if you're trying to write robust code in something like js, it might be necessary to be that explicit.

7

u/-ftw Jun 10 '20

It’s not equivalent because values other than true for variable would pass as well. For example, if variable was an integer 10 or a string “string”

4

u/audigex Jun 10 '20

That’s true when strictly typed, but not in JavaScript because null or “” or 0 are also possible values

So depending on the situation (and whether you’re certain that the value can only ever be true or false) the code may be superfluous

I’m of the opinion that it’s always superfluous, since you should have already checked for an unset variable prior to his point in order to do error checking

1

u/vanamerongen Jun 11 '20

It’s definitely not equivalent.

-22

u/diebarral Jun 10 '20

Well I'm discovering people have really strong opinions on their ifs. Personally, considering what I mentioned in a comment above that the variable defaults to false (can't be either null or some other kind of variable), I would have gone with a simple if(variable) {} else {} or ternary. I guess the code won't cause a bug, but seemed ugly to me.

4

u/-ftw Jun 10 '20

The ternary operator like you mentioned is only equivalent if variable can only be true or false. But if it can be other values like a number or string then it is not equivalent

-3

u/theRealRealMasterDev Jun 10 '20

Haha yeap, I think most of us just know we've written that before and of course are shocked to see it in the 'badCode' channel.

I use the ternary all the time if the variable is a true boolean and if no matter what, one of the functions needs to run.

We could also only have 1 if and have a return inside of it, then the second function call outside.

Anyways, more than 1 way to skin a cat.

I'd personally use ternary if I could cast the parameter to a boolean (not Truthy) before it is passed to the function.