Skip to main content

Writing code for both computers and humans

One day, I was reading some source code from the Adobe Spectrum library when I saw this JavaScript ternary expression:

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 defaultValue. If defaultValue were NaN then we get back NaN anyway.

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:

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.