IF-less Programming

Sean Shaughnessy
3 min readJun 24, 2021

There are several alternatives to IF statements in JavaScript. Today, I will be looking at a few of my favorites. These are very useful when working in React as there are limitations to what can be put in a component’s return statement. They are:

Ternary Operator (? :)

Short Circuit evaluation with &&

JavaScript Object / Enum

Optional Chaining (?.)

Ternary Operator

I use the ternary operator when there are two or three possible components to be rendered. Although ternaries can be confusing at first, they are shorter and can be used outside of React. Ternaries have a bit of a bad reputation because of all the examples of multiple chained ternaries. Consider the following example:

I probably would have put this code in an object. I prefer at most one chained ternary and there are some organizations that do not allow chained ternaries at all.

Short Circuit Evaluation

Did you know that the logical operators perform short circuit evaluation? That means that any additional parts of an AND (&&) expression are not evaluated once a falsy value is found and any additional parts of an OR (||) expression will not be evaluated once a truthy value is found. This includes side effects and code which will throw an error. In React, the && operator can be used for conditional rendering. This is useful when there is one potential component to be rendered. Just be aware of the zero trap! Look at the following code :

This will cause a zero to be rendered because 0 and NaN are the only falsy values that will be rendered by React. To prevent this, use two ! operators before the potential 0 or NaN to convert it to false.

JavaScript Object

It is possible to use a JavaScript object as an alternative to an IF or switch statement when there are many components to be rendered. Here is an example from one of my recent projects:

Objects can be used to store components and referenced later. I don’t use them as much, but they are valuable in more complicated projects.

Optional Chaining

Have you ever encountered the following error: “Can’t read property xyz of undefined”? Sometimes there may be objects that may or may not have properties. Sometimes the Internet is slow and data might not be where you expect it. Instead of writing a bunch of IF statements to check for nulls, you can use the optional chaining(?.) operator. The ?. operator can be used in place of the dot (.) operator and will return undefined if the property is null or undefined. Since it was released in 2020, you might not have heard of it. I used it in the calendar component of the Vacation Planner Group Project when I padded the calendar display with nearly empty objects.

It might seem crazy, but you don’t have to play the What IF game when writing conditional code. There are other methods out there that may be more useful.

Credit: 3 Anti-patterns for Conditional Rendering with React (frontarm.com)

--

--