Master the art of Conditionals- JavaScript

Thomas Nyambati
7 min readJan 4, 2018

--

Conditionals are very important concept in any programming language. Through conditionals we can define what piece of code should run, when and where. If you have written code before, then you have come across conditionals or implemented one in your program. Through conditionals we can make logical based decisions thus providing us with the flexibility of dynamically processing or analysing information based on the condition is true or false. A good example will be when implementing error handlers. Error handlers mostly take in a value, check if the value has any the required information, and return appropriate response based on whether there was an error or not.

Below is an example of a simple error handler.

As you will notice, we have used conditionals to ensure that the arguments passed are of the required type. And later within the for loop checked if the object passed has all the required properties. If the object is missing any required property, we can create a custom error message with is later returned by the function as shown in the code example below.

Without use of conditionals such logic will be hard to implement and probably not even possible.

Imagine how life will be if we didn’t know how to make decisions. You probably will not be reading this article right now, Scary right?.

Just as spider-man says “With great power comes great responsibility”, conditional should be used with wisely. As much as conditionals are useful, if not well implemented can be the difference between good codebase and a nightmare. When if-else statements are not properly used can lead to what I commonly refer to as IF ELSE MADNESS. This usually occurs when you codebase has deeply nested to the fact that your codebase becomes hard to read and follow.

Note: This article is opinionated, the approaches shared here are from personal experiences and are not to be sold are best practices but rather approaches one should consider adopting while working with conditions in JavaScript or any other language. Any criticism or correction are welcome.

When you implement deeply nested if-else statements, it’s easy to lose of your logic. Following through the logic can be confusing not only to you, but also to other developers working on the same project.

Above is an example of nested if/else statement, something you might need to avoid where possible. Sometimes such implementation can be hard to avoid, However try as much as possible not to find yourself in such situation. If you have nested if/else statements that look like Chinese noodles, it high time you take those chop sticks and do something.

When I was learning JavaScript, code blocks like the one above were a common occurrence, However overtime I have developed few approaches that have come in handy when it comes to implementing conditionals. In this article I am going to share approaches I use to avoid the IF ELSE MADNESS.

Note: All the examples will be in javaScript.

Break Program Logic Into Functions

Functions are statements or expression that are designed to perform specific tasks. This approach enables us to group our program logic into small chunks which can be used anywhere in our program. On of the major benefits of functions if concept of reusability. This means that one function can be used multiple times within the same program.

In relation to conditionals, we can wrap conditional logic with functions. This way we can avoid writing the same condition over and over again. Let’s assume we are building a student marks management system. And this system takes the average of all the student score are tells him or her whether they passed or not. The code to handle this might look as shown below.

The above implementation works no doubt, but there is a problem. If we need to compare the average of the students somewhere else within our codebase we will need to repeat the same codebase again. As an alternative we could wrap our logic within a function which takes two arguments — average and pass mark.

Having wrapped our logic in a function, we can use it anywhere within our program passing it different arguments.

By wrapping the conditionals within functions we can re use the logic anywhere in the codebase while still keeping our code as possible.

Use Single if Blocks

When evaluating more than two possible outcomes, you might end up chaining your if statements. Let’s assume that we have gifts classified in colours. We have been tasked with job to gifts based on user colour profile. In this context we only have 3 colours — red, blue and green. A more natural approach will be as below.

However, we can make our code more elegant by wrapping the logic within a function and using single if blocks.

With this implementation, we have only used two single if blocks with return statements. The return statement will ensure that the function will exit the moment any of the if blocks is evaluated to true, if not the last statement will be executed. This approach gives us the same functionality as the first approach but in a more cleaner way.

Using the same approach we can rewrite the hasPassedExam function as follows.

Use switch statement

The switch statement is used to perform different actions based on different conditions. It compares the expression with the values of each case. If a match is found the associated code is executed. Using the previous example, we already know the colours we are checking for. This means that we can replace the two if statements with a switch case statement.

Lets see how its done.

Note: Switch statements are only executed once.

Use ternary operator where possible

A ternary operator takes three arguments and often used a a shortcut for if else. When dealing with conditionals sometimes you need statements that evaluate to either true or false. Ternary operator takes the following syntax.

When the condition evaluates to true, expression1 is returned else expression2 . This is the same as if else state shown below.

Ternary operators are commonly used if statements. This not only reduces the number of if statements you use but makes your code more readable. Using hasPassedExamfunction as an example, we can modify it to use ternary operator as follows.

Our example might not be the best in the world but I hope you get the idea. Ternary operators are shorthand for if statements, but should not be a complete replacement for them. This means you will have to be careful where to use them.

Worst case scenario approach.

Last but not least is the worst case scenario Approach which is my favourite by the way. So what does it mean? When working with conditions, the are either two or more possible outcomes. Positive outcome - thats the good stuff i.e data from an api endpoint and the Negative outcome such as errors from database etc. When most encounter such they opt to handle the good stuff and the errors later. As much as the logic works, you will end up with more if statements that you should.

Let’s look at an express app controller for creating MongoDB document.

This is where the worst case approach comes in. “Always handle the worst scenarios first”. What this means is that whenever you are handling multiple scenarios start with the worst and finish with the good. This approach not only enables you to write cleaner code, it also makes it easier to cater for all the edge cases.

As much as it can work on any situation, This approach should be used with combination of the above mentioned trick where possible. This solidifies your approach and makes your code more clear and cleaner.

We can refactor the above code using this approach as follows.

This gives us more cleaner code which is much easier to read, understand and maintain.

Conclusion

There are many approaches that can be adopted manage how conditions are implemented. Some of these approaches include functional programming, recursions .etc. It will be upon you to decide what approach works for you and how to implement it. Code is a developer’s story, you decide how to tell it because the world will remember you by it. In other words Write beautiful Code at all times.

--

--

Thomas Nyambati

Full stack developer | DevOps Engineer |Author |Tech Evangelist |