If vs Ternary vs Switch-Case for conditionals

Tuesday, May 5, 2020

by  Etin Obaseki  Etin Obaseki

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.