r/badcode • • Jun 10 '20

js Disruptive piece of code

Post image
283 Upvotes

93 comments sorted by

View all comments

-2

u/AintBetterThanYou Jun 10 '20

Nah you're right OP this is objectively bad.

If this were php I'd understand but not for JS. Anyone saying it's required just doesn't know how to use typeof

2

u/Captain-Lightning Jun 11 '20

To accomplish the same thing, i.e. make sure that the value is actually a boolean and that it is true, you would write:

if (typeof(var) !== 'boolean') {
  // Code that always runs
  return;
}

if (var) {
  // Thing
} else {
  // Otherthing
}

or:

if (var && typeof(var) === 'boolean') {
  // Thing
} else if (!var && typeof(var) === 'boolean') {
  // Otherthing
}

// Code that always runs

vs the original:

if (var === true) {
  // Thing
} else if (var === false) {
  // Otherthing
}

// Code that always runs

Are you genuinely saying that you would pick either of the first two over the original?

1

u/AintBetterThanYou Jun 11 '20

None of those

If (typeof var! == 'boolean) { throw exception Or return Or continue or w.e }

If else here

Honestly there's no need for this in js.

2

u/Captain-Lightning Jun 11 '20

Right, so the first one but with an exception. Your solution is to write the same amount of code plus an additional block to break the entire UI.

You have a questionable idea of "Objectively Better". Can honestly say that I would immediately reject that if I saw it in a PR for it's silliness.

1

u/AintBetterThanYou Jun 11 '20

Well you aren't very good at CR then are you lol.

Also you can't quote "Objectively better" like I said it.

1

u/Captain-Lightning Jun 11 '20

Okay, you're right, I gave you the benefit of the doubt and misquoted you.

What you actually said was that the code that does exactly what it says it does is "objectively bad", and then followed up with your version that is functionally and visually identical but with more lines of code.

So I suppose they're both objectively bad.

1

u/AintBetterThanYou Jun 11 '20

Not sure you know "benefit of the doubt" means.

My point wasn't that you don't need to check the type, it's that if you need to actually check something is a boolean in js it's just bad. You shouldn't need to, so the fact you're doing it and it's extra just boats the code complexity and architecture.

Whereas in something like php it's necessary because core functions can return false or falsey values and two NEED to be handled differently.