Member-only story

5 Alternatives to ‘If’ Statements for Conditional Branching

Concepts for implementing conditional branching with examples in JavaScript

Jamie Bullock
Better Programming
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:

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:

Create an account to read the full story.

The author made this story available to Medium members only.
If you’re new to Medium, create a new account to read this story on us.

Or, continue in mobile web

Already have an account? Sign in

Responses (8)

What are your thoughts?