3 ms·
Even if the author was right about the intent, I would disagree with them that “this is how to write code with empathy for other programmers”, because the code
by layer8 3y ago
Even if the author was right about the intent, I would disagree with them that “this is how to write code with empathy for other programmers”, because the code would just make me think “I must be missing something” (and indeed the author did miss something).
My theory, by the way, was that the expression is normalizing the possible NaN representations to a definite one, possibly to prevent transporting information via the NaN representation.
Such “what the …?” code should have a comment explaining the intent (e.g. “replace non-numeric values by NaN”). If it is used in multiple places, that’s a good opportunity to define a function for it, so the intent only needs to be documented in a single place. (In programming languages with annotations as a language construct, annotations could alternatively also be used for referencing the documentation of a coding pattern from multiple places.)
- josephg 3y agoYeah I absolutely agree. The intent of that code isn’t clear - and if you need more proof, look how many different opinions there are in this thread about what that code is trying to do! Anyway, if they’re trying to coerce non-numbers into NaN, I’d write it like this: typeof defaultValue === “number” ? defaultValue : NaN I think that’s much more clear about the intent. I wouldn’t be confused by that code like I was confused by the code cited in the article.