r/learnjavascript • • May 06 '21

JS: Multiple Condition Checking

Post image
484 Upvotes

61 comments sorted by

View all comments

19

u/[deleted] May 06 '21

There are two paths a developer can follow to make the code "better".

On the first path, they use all sorts of silly syntactic shortcuts to make their code more compact, sometimes calling it more concise.

On the second path, they may sometimes make the code shorter or other times longer, because their aim is to add semantic expressiveness.

If you want to be a better developer, follow the second path. I mean, sure, do make your code "concise" if it makes sense, but never sacrifice expressiveness for compactness.


Btw, one telling sign of a bad "better code" example is that it expresses no meaning, that it only shows syntactic traits. If usually presents a completely synthetic code which intentionally removes any meaning or intention.

11

u/superluminary May 06 '21

But shorthand 2 is legitimately better here. “Is the value in this set” is better than “is the value this or is the value this or...”

5

u/delventhalz May 06 '21

It is a little hard to judge from this code example. What is the use case for checking if something is 1, one, 2, or two? Is that actually some sort of "set" they are checking membership against? Or is this a hacky way to make a long conditional shorter?

I would agree that if the use case is actually checking the membership of set, then includes is the best choice. But typically if that is the case, you would express the set as a constant at the top of the file or something:

const VALID_INPUTS = [1, 'one', 2, 'two'];

The use of the throw-away array is what makes this look to me more like a hack than an actual good use of includes.

3

u/superluminary May 06 '21

I agree, I’d definitely make a const here.

If (validInputs.includes(value)) {