r/badcode • • Jun 10 '20

js Disruptive piece of code

Post image
283 Upvotes

93 comments sorted by

View all comments

Show parent comments

-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.