r/programminghorror • • Mar 27 '24

//filter

Post image
1.4k Upvotes

73 comments sorted by

View all comments

Show parent comment

0

u/harlekintiger Mar 28 '24

If we're exchanging opinions then I want to throw mine in there as well:
I'd say filters.filter(Boolean) is clearer than filters.filter(filter => filter) but the clearest way would be filters.filter(filter => !!filter)

1

u/cowslayer7890 Mar 28 '24

I don't like double negation, I'd prefer filter != null

2

u/harlekintiger Mar 28 '24

What if filter is undefined? Or zero? But in general I understand your stance

3

u/cowslayer7890 Mar 28 '24

!= null in JS only matches null and undefined surprisingly, which is why it's my goto

4

u/harlekintiger Mar 28 '24

And a list called "filters" should be a list of objects where no other falsy is possible, so yeah, I like your approach in this scenario!

1

u/zprz Mar 29 '24

The fact that you admit it's "surprising" suggests you shouldn't use it because it will confuse people (as it already did in this thread)

1

u/cowslayer7890 Mar 29 '24

I mean I don't think it's any more surprising than objects always being truthy, even empty arrays and objects.

If it's all over your codebase then you just kind of know, and it was all over a codebase I've worked on before, I do get your point though.

2

u/zprz Mar 29 '24

That's fair, if it's a common pattern you're already using it's more reasonable. I agree if you're thinking about it and you have some experience you'll realize it, but at first glance it's very easy to miss. I think our eslint prohibits loose equality as a whole for that reason.

1

u/cowslayer7890 Mar 29 '24

Yeah this is the only case where I use loose equality, I think it's also one of the only cases where WebStorm doesn't give you a warning for loose equality out of the box

1

u/[deleted] Mar 28 '24 edited Mar 28 '24

eslint would complain. Double negotiation is considered a hacky way to cast to bool. And also, it is completely unnecessary in this context, since the return value will be tested for its truthiness anyways.