Hacker News new | ask | show | jobs
by williamdclt 396 days ago
> What do you think about empty strings being falsy in most languages including js?

I don’t love it! I think it’s inconsistent with empty arrays being truthy.

In practice, I see a lot more mishandling of empty strings than empty arrays (eg “!myvar” catching null and empty strings when it’s not what was meant) which hints that it’s not the right thing to do: an empty string is a valid string, whether its semantically different from non-empty entirely depends on the context and shouldn’t be baked into the langage.

Generally, I think implicit casts are not a great idea and I’d rather they didn’t exist (one of the few things I think Go got right).

> For example with document.querySelectorAll, which returns an empty array if nothing is found

Yes I think it’s doing the right thing. It’s indeed returning the list of elements, whether there’s 0 elements or more it’s still a valid list. As you say, you don’t usually need to handle it any differently from a non-empty array (just iterate), so I don’t think it should cast to a different value.

However if for example you were passing something like a whitelist as an argument, I’d expect [] to mean “there is a whitelist, allow only these items (ie allow nothing)” and null to mean “no whitelist, everything allowed”. These two things are semantically different, I think it makes sense to cast to different values.

I do see your point and it’s definitely at least partly a matter of taste. Again id rather there was no implicit conversion at all, removing the risk of mishandling altogether!