How to shorten if/else statements in Javascript

If there’s ever a programming concept that should be carved on a stone tablet, it’s the if/else statement.

If something is true, do this. If it’s not, do something else. An if/else statement is foundational. We’re telling the system to make a choice.

But the syntax can sometimes be long and clunky. Solving smaller conditions with a big if/else statement is like patching that big scrape on your car with a can of spray paint. It works, but it could be a lot better.

While building the compound interest calculator, I finally learned a shorter way that the rest of the world has probably been using for years.

Enter the ternary.

It does the same job and sounds way cooler when you tell your friends about it.

Say we want to find out if a number is something other than zero. We want to write a different result on the page depending on what the number is. In ancient times, I would use this:

if(number == 0){

document.write(“This number is just a zero.”);

}else{

document.write(“This number is definitely not zero, it is definitely a value!”);

}

And if there are multiple conditions you’re looking for, this method still works.

But what if I told you there was a shortcut? The ternary checks a single condition and does different things if it is true or false.

Condition ? First action : Second action;

The part before the ? checks our condition. In the example above, that would be number == 0. After the ? Come our options for action. The first action will be performed if the preceding condition is true. The second action will be performed if the condition is false, just like our else statement.

Our example would look like this in a ternary:

number = 0 ? document.write(“This number is just a zero.”) : document.write(“This number is definitely not zero, it is definitely a value!”);

Simple and shorter. Ternaries are especially useful when you’re changing numerical values or dealing with a lot of variables and conditions.

You can read much more about our friend the ternary operator here through the Mozilla Developer Network.