Member-only story
5 Alternatives to ‘If’ Statements for Conditional Branching
Concepts for implementing conditional branching with examples in JavaScript

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…