DEV Community

Etinosa Obaseki
Etinosa Obaseki

Posted on • Edited on

If vs Ternary vs Switch-Case for conditionals

Conditionals are programming structures that determine the flow of the program based on an evaluation.

In most C-style languages, such as JavaScript, there are multiple ways of handling conditional logic.

In this article, I'll discuss the if-else, ternary operator, ? and switch-case and how I decide which to use for different situations.

Whenever I write code that will need to be maintained either by myself or someone else, I like to consider the developer experience of that code.

Will I (or the eventual maintained) easily be able to grasp the purpose of the code? Am I likely to misunderstand what the code actually does? Does the code significantly deviate from expected affordance?

If-Else vs Ternary

let isEvenOrOdd = number => {
    if(number % 2 == 0){
        return "Is Even"
    }
    else {
        return "Is Odd"
    }
}

For scenarios with this-or-that (only two possible) outcomes, I prefer to use a ternary because it's less code for the maintainer to parse. In a large project, those could be a lot of lines saved.

let isEvenOrOdd = number => {
    return number % 2 == 0 ? 
        "Is Even" : "Is Odd"
}

However, for more complex conditionals we may need else ifs

For example, a conditional with three possible options.

let meal = null
if(time == "morning") {
    meal = "breakfast"
} else if(time == "afternoon") {
    meal = "lunch"
} else {
    meal = "dinner"
}

We could handle this case with a ternary operator(s) as well.

let meal = null
time == "morning" ?
    meal = "breakfast"
    :
    time == "afternoon" ?
        meal = "lunch"
        :
        meal = "dinner"

Of course, despite looking fancier than ordinary If-Elses, this is probably less readable than the previous example.

Let's switch this up a bit.

Switch Statements

Switch Statements allow us to evaluate several cases against a single expression.

Our meal example from above would be represented thus:

let meal = null
switch(time) {
    case "morning":
        meal = "breakfast"
        break
    case "afternoon":
        meal = "lunch"
        break
    default:
        meal = "dinner"
}

Conclusion

Switch statements are versatile and could provide a more readable alternative to If-Elses and ternary operators.

Top comments (4)

Collapse
 
harleybl profile image
harleybl • Edited

Did you mean for the afternoon case in the last example to fall through to dinner? The way it is written you’ll never get lunch because of a missing break.

Collapse
 
obasekietinosa profile image
Etinosa Obaseki

Ah. No I didn't.
Thank you for pointing that out. I'll fix it right away.

Collapse
 
harleybl profile image
harleybl

No problem. The article was good otherwise.

Thread Thread
 
obasekietinosa profile image
Etinosa Obaseki

Thank you. Glad you think so.