DEV Community

Muhammad Muhktar Musa
Muhammad Muhktar Musa

Posted on

Conditional logic you should know

Once you start getting JavaScript under the belt, one of the things you would want to do is get conditional logic into an application. What is conditional logic? Conditional logic acts as a traffic curve in a program. It decides which conditions are to be prioritized if the logic is true. It also decides the code to run or what to do if the condition is false. This conditions can be used to run different things based on different values.
Let us take a look at 3 different conditional logic in javaScript. We want to know what they look like and when they are to be used to optimize an application .

If/else statement

We are going to look at an array of food and each food is represented an objects.

 const food = [
    { type: "Banana", family: "fruits" },
    { type: "Lettuce", family: "vegetable" },
    { type: "Rice", family: "grains" }
  ]
Enter fullscreen mode Exit fullscreen mode

We are going to use a javascript forEach method to loop through the contents of the food array and execute the function using the if/else statement.

food.forEach (({type, family})=>{
if (family === "fruits"){
  console.log(`i am eating ${type}`);

}if (family === "Vegetable"){
  console.log(`i am eating ${type}`);

}if (family === "grains"){
  console.log(`i am eating ${type}`);

}
  });

Enter fullscreen mode Exit fullscreen mode

When we run the above code we get the current value that we loop over and introduce our conditional logic. All we are doing is saying if the condition is met run the code or other wise move to the next statement. That is the basic idea behind an if statement. It is a very simple but powerful tool. We can apply an else statement to the if statement. For example we can say

food.forEach(({ type, family }) => {
    if (family === "fruits") {
        console.log(`i am eating ${type}`);

    } else if (family === "Vegetable") {
        console.log(`i am eating ${type}`);

    } else if (family === "grains") {
        console.log(`i am eating ${type}`);

    }
    else { console.log('all food are good for hunger'); }
});
Enter fullscreen mode Exit fullscreen mode

When we give a condition to the if statement, if the condition is true we are going to log a statement otherwise we log whatever the else statement is when the if statement is through no matter the value we are looping through. As long as it does not meet our if statement the else statement will be logged.

Switch statement

The next type of logic we are going to look at is the switch statement. The switch statement is similar to the if/else statement. We going to take a look at a similar food array and loop through using the switch statement


const getFoodAll = (food) => {
    switch (food) {
        case "Banana":
            return "this is my favorite fruit";

        case "Lettuce":
            return "this is my favorite Vegetable";

        case "Rice":
            return "this is my favorite grain";
        default:
            return "i have no business being here";
    }
};
Enter fullscreen mode Exit fullscreen mode

Unlike if/else statements, the switch statements keep going. They do what is called fall through. What it does is print all the statements when the conditions are met. To prevent all the statements falling through, a break statement is added.

const getFoodAll = (food) => {
    switch (food) {
        case "Banana":
            return "this is my favorite fruit";
            break;
        case "Lettuce":
            return "this is my favorite Vegetable";
            break;
        case "Rice":
            return "this is my favorite grain";
            break;
        default:
            return "i have no business being here";
    }
};
Enter fullscreen mode Exit fullscreen mode

When using the switch statement, in some cases we want to fall through all the various cases. In some other cases we want to break the code when we have our result. The break is known as the stop mechanism for achieving this. When we hit a statement we want evaluated the break stops the code from evaluating all other statements from that point. This break stops the steady flow. If we don't have a break, the code is going to run to the default statement. The switch statement is super useful in replacing logic that uses a lot of if/else statements.

Ternary operator

It is a simple piece of very powerful code. It is the only JavaScript operator that takes three operands: a condition followed by a question mark (?), then an expression to execute if the condition is truthy followed by a colon (:), and finally the expression to execute if the condition is falsy. This operator is frequently used as a shortcut for the if statement.

function lifeStyle() {
    if (condition1) { return value1; }
    else if (condition2) { return value2; }
    else if (condition3) { return value3; }
    else { return value4; }
}
Enter fullscreen mode Exit fullscreen mode

Using the tenery operator the above logic can be simplified into

function lifeStyle() {
    return condition1 ? value1
         : condition2 ? value2
         : condition3 ? value3
         : value4;
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)