Better Programming

Advice for programmers.

Follow publication

5 Alternatives to ‘If’ Statements for Conditional Branching

Concepts for implementing conditional branching with examples in JavaScript

Jamie Bullock
Better Programming
Published in
4 min readSep 9, 2020

--

SVG by Booyabazookaoriginal; PNG by Wapcaplet / CC BY-SA

Conditional branching is when a segment of code is executed or evaluated based on a condition, typically implemented using an if...else construct.

For example:

if (customerPaid)
{
sendThankYou()
}
else
{
sendReminder();
}

Here, sendThankYou() will get called if customerPaid is true; otherwise sendReminder() will be called.

There’s some thinking in the programming community that if should be considered harmful or a code smell. Regardless of the validity of this claim, there may be cases where if isn’t the best approach to branching, or where branching should be avoided altogether.

In this tutorial, I’ll therefore demonstrate six alternatives to if...else with some discussion on when you might choose to use them.

Examples are written in JavaScript, but the concepts are applicable in many other languages.

1. The Ternary Operator

One of my favourite alternatives to if...else is the ternary operator.

This takes the form:

condition ? expressionIfTrue : expressionIfFalse

Here expressionIfTrue will be evaluated if condition evaluates totrue; otherwise expressionIfFalse will be evaluated.

The beauty of ternary operators is they can be used on the right-hand side of an assignment.

For example:

const labelText = customerPaid ? "Thank You!" : "Payment Overdue";

This will set labelText to “Thank You!” if the customer has paid; otherwise, you’ll get “Payment Overdue”.

2. The Switch Statement

A switch statement has the following structure:

--

--

Responses (8)

Write a response