01. Nested Ternaries // JavaScript Codecasts

Toggle fullscreen Fullscreen button

Sharing buttons:

How many times does “else if” appear in your codebase?

Let’s examine one way you can cut down on if-else statements in today’s episode of

TL;DR, the JavaScript codecast series that teaches working web developers to craft exceptional

software in 5 minutes a week.

The if-else statement is probably the first control flow construct you learned as a programmer.

And yet few things are as terrifying as diving into a legacy codebase swimming in nested,

cascading if-else statements.

Code with fewer if-else statements is generally less complex because it has fewer edge cases

that need to be tested, and code with fewer statements tends to have a more predictable

program flow.

A program without any if-else statements or other conditional constructs is incredibly

straightforward to reason about, because data will always flow through the program in the

same way, even when the inputs and output change.

Now it’s unlikely you could eliminate all if-else statements from a program without

making readability worse off.

But a lot of if-else statements is a code smell, because they unnecessarily increase

the complexity and surface area for bugs.

So in the next few episodes of TL;DR we’ll cover some design patterns to cut down on

if-else statements.

Today we’re examining some recursive code with several cascading if-else statements.

This resolve function walks through an object with nested objects, arrays and functions.