Ternary Operators in Javascript aren’t just harmful, they’re selfish and evil

 
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.

Bonus:

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.


"no-nested-ternary": [2]

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).

One thought on “Ternary Operators in Javascript aren’t just harmful, they’re selfish and evil

  1. > Apart from being ugly

    Very very often (when the expression is complicated), but not always.

    > confusing

    Very very often (when the expression is complicated), but not always.

    > and error prone

    When used in the right place, they secure us from errors; while an if could lead to a disaster.

    > ternary operators are a premature optimisation

    They are not any kind of optimization; could you elaborate your perspective.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s