When talking about clean code there are some things that most programmers will pay attention to. Naming things well or using short function bodies are two examples. But there are other, more subtle code smells that can make your code hard to understand. One thing I recently stumbled upon in a code review is the structure of conditional logic. Have a look at the following JavaScript snippet. Can you immediately tell what the output is?

const array = [1, 2, 3];

if (0 < array.length) {
  console.log('The array has values');
} else {
  console.log('The array is empty');
}

This isn’t a trick question and you’ve probably observed correctly that the code will print “The array has values”. But how much cognitive effort was necessary? You probably had to look at the code at least twice.

Now here’s the same thing, but different.

const array = [1, 2, 3];

if (array.length > 0) {
  console.log('The array has values');
} else {
  console.log('The array is empty');
}

Much easier, right?

Imagine having to explain the logic to another person. You would probably start with something like
“When the array length is greater than zero the output is ‘The array has values’.”

What you wouldn’t say is
“When zero is less than the array length, the output is ‘The array has values’.”

The array length is of interest here, so it should be the subject of the sentence. In the second example, the subject is inverted, similarly to the 0 === array.length expression. The syntax is correct, but the semantics are obscured. Your mind isn’t accustomed to that and trips up when it stumbles upon it. It then has to do another roundtrip to understand the expression. This illustrates the conclusion of this article: conditional expressions should be structured like natural language.

Your mind is trained to understand natural language. Structuring your code similarly will make it simpler to read and understand. It’s a subtle change, but it can make a huge difference when code becomes more complicated. Keep it in mind the next time you write a conditional expression.