How To Use Conditional Statement In Javascript

How To Use Conditional Statement In Javascript

Life is a pot of beans. Life has been defined as many things by many people. You may or may not have heard of the description I used but it doesn’t take away the fact that life is unpredictable and it is as a result of this unpredictability that we react in a certain way based on certain actions. Because computer programmes are built to interact with humans directly or indirectly, programming languages have inbuilt features that make them able to cater to the uncertainties of human behavior. This feature is known as “Conditional Statement''. Javascript is one such programming language that have to interact with humans a lot so we will be talking about Javascript today.

It is commonly believed that there are three types of conditionals statements. According to Pluralsight, we have; If statements, Else statements, and Else If statements. I’ll demystify them below.

If Statement: It should be used when there aren’t many uncertainties, majorly if there are only ways a scenario can play out, use If statements, It basically is built to wait for/or handle one scenario. E.g

if (10 > 5) {
      var outcome = "10 is greater than 5";
}
Console.log(outcome);

Else Statement: This is used when you want the program to respond to two scenarios that can play out. E.g

if (5 > 10) {
      var outcome = "5 is greater than 10";
} else  {
      var outcome = "5 is not greater than 10";
}

Console.log(outcome);

Else If Statement: This is used when there are many ways a scenario can play out and you want to be able to respond to as many of them as possible. As a silent rule, you don’t want to use too many Else If statements and it creates what we call “Spaghetti Code” because of how messy it looks. If you’re using above 4 Else If Statements then you must be doing something wrong and you need to explore other ways to solve that challenge. Else If Statements should always end with an Else statement which is more or less a failsafe feature that will handle scenarios you didn’t plan for eg.

if (10 > 10) {
      var outcome = "10 is greater than 10";
} else if {
      var outcome = "10 is not greater than 10";
} else  {
      var outcome = "10 is equal to 10";
}

Console.log(outcome);