Quick Tip: How to Simplify an IF Statement

Comparisons do not always need IF statements.

Posted by Malcolm Hollingsworth on

If you normally use an IF statement to branch logic in your app, there is another way to try that might sometimes be better.

This is a common method of determining the state of a variable before branching code based on the result.

var isRed = true;
if (isRed == true) {

A better example understands that the IF statement is a 'logical comparison' already, so is looking for TRUE, which means stating true is redundant.

var isRed = true;
if (isRed) {

We can reduce the comparison block if suitable; just be aware of readability issues if you go too far.

var isRed = true;
if (isRed) { doRedSomething(); }
Never be tempted to go one further and remove the curly brackets in your code.
If you are smart enough to know why this is a bad idea then you should be smart enough not to do it.

Now the real simplification of your IF block.

var isRed = true;
isRed && doRedSomething();

We simplify the if block by removing it. Yes; seriously.

The important thing here is that logical comparisons work in-line. So in our example we place the thing we are comparing at the start, then use && to say the LEFT must be true and if so then move to the right.

This is a very simple example, but if we add an extra couple of variables you can see how this simplification makes life easier and your code easier to read (sometimes).

function doRedSomething() { console.log('Red'); }
function doGreenSomething() { console.log('Green'); }
function doBlueSomething() { console.log('Blue'); }
function doAnySomething() { console.log('Any'); }
var isRed = true;
var isGreen = false;
var isBlue = true;
isRed && doRedSomething();                        // shows red
isGreen && doGreenSomething();                    // shows nothing
isBlue && doBlueSomething();                      // shows blue
(isRed || isGreen || isBlue) && doAnySomething(); // shows Any

You can use this technique in many different ways; as long as you remember the comparison is performed from left to right. Each comparison in turn must be true in order to proceed to the next one and so on.

All example code written here is in JavaScript, however many other programming languages support this reduction technique.

Using this technique is not always ideal, you may not find it as readable as the more common IF block.