March 15, 2023
These Alternatives to `if` Will Make Your Code 100x Better
Traditional conditionals can be highly damaging to your code. A few simple strategies can help protect you from harm.

By James Marks
6 min read
The Problem:
Code that is easy to understand and easy to change is key to productivity and success. While performance is important, a codebase that can't evolve with your business is working against you.
By focusing on code that reads like a book, with each passage having meaning in itself and told in sequence, you can achieve easy-to-understand code. Traditional conditional structures such as if and switch can lead to issues as your code base evolves.
However, there are alternative methods to conditionally handle code that are more extensible, powerful, and beautiful.
Let's look at how we can write code differently to reduce complexity and increase ease of understanding!
Case A: Simple max function:
In our first case, we have a small and seemingly innocent function.
This first example has 9 total lines of code. On this smaller scale, it doesn't seem so dangerous โ but it will serve as a way to see how we might make different micro decisions in a way that can apply in larger or more complex context.
Start:
function max(a, b) {
let x;
if (a > b) {
x = a;
} else {
x = b;
}
return x;
}function max(a, b) {
let x;
if (a > b) {
x = a;
} else {
x = b;
}
return x;
}Much of the issue with if is in the else block.
Having an else almost always leads to variables that are changed in more than one place.
Again, at this smaller scale it doesn't seem very harmful, but in practice, this typically leads to multiple developers making multiple changes to the same variable throughout your code, making it more difficult to trace a change.
"Good" Improvement: Early return:
One solution is to not assign to a variable at all. return short circuits a function, so let's just check if one number a is greater, and if it is return that number. Otherwise we can return the other number, b.
function max(a, b) {
if (a > b) {
return a;
}
return b;
}function max(a, b) {
if (a > b) {
return a;
}
return b;
}This is a quicker read. Now we're down to 6 lines of code. With fewer characters on the screen, our brains can more quickly understand what is happening. This small thing repeated over your code hundreds of time already results in quicker code comprehension, and thus higher productivity over the long run.
However, early returns are not always an option with an if statement. Sometimes your if statement isn't packed so neatly inside a function. For those instances, we need something different.
"Better" Improvement: Ternary expression
Another alternative is to use a ternary expression. It works in almost every case where you have only two possible actions you want to take. When you want to branch either one way or the other in your logic, this is a perfect go-to.
function max(a, b) {
return (a > b) ? a : b;
}function max(a, b) {
return (a > b) ? a : b;
}We're now down to just 3 lines, one return and a fairly simple and obvious branch.
Just keep in mind that ternaries are intended to perform assignment. I've seen people try to use them to execute side effects. In those cases, ternaries may make your code more difficult to read or change. If your ternary doesn't come after an = or a return , you may want to question if you've taken this too far.
Bonus "Best" Improvement: Arrow function
As a bonus, I'm adding the arrow function version. Its a bit more concise and looks great on a single line.
const max = (a, b) => ((a > b) ? a : b);const max = (a, b) => ((a > b) ? a : b);Case B: If/else-if/else
Here is a more complex example of an if statement. It too looks innocent at first โ especially when you don't have a great deal of experience.
/**
* `content` is expected to be a string containing text from a document.
**/
function guessDocumentType(content) {
let contentType;
if (content.startsWith('<!doctype html>')) {
contentType = 'html';
} else if (content.startsWith('---\\n')) {
contentType = 'yaml';
} else if (content.includes('##')) {
contentType = 'markdown';
} else {
contentType = 'text';
}
return contentType;
}/**
* `content` is expected to be a string containing text from a document.
**/
function guessDocumentType(content) {
let contentType;
if (content.startsWith('<!doctype html>')) {
contentType = 'html';
} else if (content.startsWith('---\\n')) {
contentType = 'yaml';
} else if (content.includes('##')) {
contentType = 'markdown';
} else {
contentType = 'text';
}
return contentType;
}In a small-sized, proof-of-concept product, like a school project, this doesn't have any apparent problems. It usually doesn't in these cases.
But hopefully, you will find yourself on a team working collaboratively on a much larger code base and at that time, your code choices will matter a great deal. Organization, portability, readability and maintainability will become the most important things to consider when writing your code.
If you want to create high quality code, you have to think about the simple things you do in more detail and begin to understand their weaknesses, as well as other strategies for solving the same problems.
A "Good" (sort of) Alternative:
const docTypeComparers= {
html: (content) => (content.startsWith('<!doctype html>')),
yaml: (content) => (content.startsWith('---\\n')),
markdown: (content) => (content.includes('##')),
}
function guessDocumentType(content) {
const matchedKey = Object.keys(docTypeComparers).find((key) => docTypeComparers[key](content));
return matchedKey ?? 'text';
}const docTypeComparers= {
html: (content) => (content.startsWith('<!doctype html>')),
yaml: (content) => (content.startsWith('---\\n')),
markdown: (content) => (content.includes('##')),
}
function guessDocumentType(content) {
const matchedKey = Object.keys(docTypeComparers).find((key) => docTypeComparers[key](content));
return matchedKey ?? 'text';
}This first alternative is a step in the right direction.
Looking at this snippet may help you to see conditional problems from another angle. I won't recommend using this option, as there is a better alternative, but I do think its worth looking at this just to add some fodder for the way you think about your code.
It isn't truly a great solution on its own, but it does do some positive things compared to the code we started with.
- It demonstrates how the code can become more concise and readable through the use of arrow functions.
- The code is made more readable by isolating comparison logic into a clear area of the code, separate from the business logic that uses them.
- Makes it easier to add or remove document types without making extensive changes to the function.
- When another developer comes to this page to add a new document type comparer, it will be immediately clear where and how to do that, without modifying the existing business logic.
But it does have its weaknesses:
- Most Javascript developers know what Object.keys() is and does, but using it in this way can make the code a bit difficult to see at a glance, which means it isn't as easy to understand as we'd like.
- Additionally, the duplicate use of
docTypeComparerson the same line along with some other "extra" code, makes the line a bit repetitive - nearly "ugly. It probably makes more nit-picky developers stop-up because all they want to do is "clean it up". - There is a mental "hiccup" looking at the code. As with your start point, this doesn't seem like a big deal in isolation, but in a larger app where another developer has to parse hundreds of lines of code like this, it can take much longer to get their head around what is happening before they can begin work on a new task.
A "Better" Alternative:
const docTypeComparers = [
{ docType: 'html', isDocType: (content) => (content.startsWith('<!doctype html>')) },
{ docType: 'yaml', isDocType: (content) => (content.startsWith('---\\n')) },
{ docType: 'markdown', isDocType: (content) => (content.includes('##')) },
];
function guessDocumentType(content) {
const matchedItem = docTypeComparers.find(({ isDocType }) => isDocType(content));
return matchedItem?.docType ?? 'text';
}const docTypeComparers = [
{ docType: 'html', isDocType: (content) => (content.startsWith('<!doctype html>')) },
{ docType: 'yaml', isDocType: (content) => (content.startsWith('---\\n')) },
{ docType: 'markdown', isDocType: (content) => (content.includes('##')) },
];
function guessDocumentType(content) {
const matchedItem = docTypeComparers.find(({ isDocType }) => isDocType(content));
return matchedItem?.docType ?? 'text';
}This solution is similar to the "Good" one above, except that we've now arranged the comparers into an array of individual objects rather than an object. Each array item comes with a docType field indicating the document type if matched and an isDocType field containing the comparer function.
It is still fairly obvious to a developer how to add new comparers and the guessDocumentType function becomes much easier to read.
As an added bonus, naming the fields of the comparers, helps them to be "self-documenting".
Bonus "Best" Alternative:
import { comparers } from './comparers';
function guessDocumentType(content) {
const matchedItem = comparers.find(({ parse }) => isDocType(content));
return matchedItem?.docType ?? 'text';
}import { comparers } from './comparers';
function guessDocumentType(content) {
const matchedItem = comparers.find(({ parse }) => isDocType(content));
return matchedItem?.docType ?? 'text';
}This is simply a further extension of the previous array alternative. But, instead of holding the details of the functions in this file, you import them from another file for organization purposes. This opens the door to further separation of concerns, which would be incredibly useful for a growing list of potential alternatives that each may have heavier complexity.
Much of the time, if you have a shorter list of items to compare, you'd stick with the "better" alternative. So long as you've prepared it in that way, it isn't very difficult to refactor your work to progress to this.
(In a future article, I may provide an in-depth look at how this might be done by example.)
Get Coding!
I hope you found this article helpful, useful, and interesting!
Keep an eye out for my next few articles where we'll explore alternative strategies to other common paradigms. We'll start by taking a closer look at switch.
I'm excited to share more ways to improve your code and make it more maintainable, readable, and productive.
Happy coding!
Check out one of my other articles below:
I Use This Alternative to switch to Make Javascript 10 Times Better
Make your Javascript code more flexible, readable and maintainable with this one simple alternative to switch.
Why Typescript is Better than JavaScript for Team Projects The Unending Debate: Why Use Typescript?