isNaN(defaultValue) ? NaN : defaultValue;
This made me pause for a moment. The logician in me was confused why such an expression was necessary—this ternary is equivalent to just using the value of
NaN then we get back
But then I realized that this code lead me through that thought process in the first place because it was written this way. If you think about it, this code expresses a lot of information:
defaultValueis going to be a number
- It is possible that the value is
- The author who implemented this code considered and handled this possibility
NaNvalue is explicitly forwarded through
Now consider the alternative. What if the author left this as just
defaultValue? If you saw that, your spidey-sense might start tingling, “This is a number—did they consider the
NaN case?” To answer this question, you need to start looking around for clues. Maybe they left a comment explaining this, but more often you will need to read the surrounding code to find out. Or worse, run some tests. Or worse worse, write new tests. Or worse worse worse, run the app and manually test!
This ternary is much better. This is expert-level programming. This is how to write code with empathy for other programmers.
I tip my cap to @snowystinger (who wrote this expression, and best as I can tell) and the rest of the Spectrum team.