I recently spent many hours pouring over the CodeMirror source code in an attempt to track down a number of unpleasant bugs that turned what should have been a straightforward and quick update to my Brackets editor extension ‘Go To Matching Bracket‘ into a day-long slog.
The main reason for the wasted time? The unnecessary and excessive use of ternary operators (and ternary operators inside ternary operators inside ternary operators), whose soul intention seems to be nothing more than to obfuscate logic at every opportunity. Oh, and to save a few characters typing, because the web is short of characters and we don’t want to use them all up.
Apart from being ugly, confusing and error prone, ternary operators are a premature optimisation and usually turn simple refactoring into rewriting – they can rarely be sensibly expanded upon without reverting back to using a regular if/else statement (or heaping more stupid on top of the existing stupid).
So, next time you’re thinking about using a ternary operator, stop for a minute, read David Hayes excellent essay ‘Ternary Operators Considered Harmful‘ then… don’t. Just don’t.
If you’re using the excellent ESLint to improve the quality of your code then you can minimise the destruction that ternary operators wreak by enabling either the no-ternary or no-nested-ternary rule in your .eslintrc config file.
Add either of these rules, run ESLint in a Git pre-commit hook and you’ll never waste your colleagues time again (well, not with ternary operators anyway).