Overusing the Ternary Operator

If you’ve ever gone head-first into someone else’s code, you’ve probably found some interesting things.

At Hexient Labs we refactor a lot of existing codebases for our clients. Normally, the code is cohesive, and easy to reason about. Last week; however, I ran across an interesting snippet.

return a && b ? a >= b ? 1 : -1 : 0;

Sure, it’s succinct; however, it’s riddled with obfuscated logic. I had to take a minute think about what this actually does. This line of code actually made my job as a maintainer of a project more difficult.

Writing Maintainable Code

As developers of production systems, it’s our responsibility to diligently write maintainable, readable code. One of our key goals should be to make our work human-readable and require low cognitive load of our readers.

Our job is not done once we deploy to production. There are constant bug fixes and feature requests. The biggest favor you can do for yourself and your team is to take your time, deal with a few extra keystrokes, and write clean code.

Please, use an if statement:

if (!a || !b) {
return 0;
} else if (a >= b) {
return 1;
return -1;

One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.