DEV Community

Adam Crockett 🌀
Adam Crockett 🌀

Posted on

Learning to ️ switch statements

For many years I used if because why not, it does everything I need. Then I met Rust, we where inseparable. Rust showed me the match statement and I started thinking about simplicity, code meaning, safety, minimal solutions and code correctness.

JavaScript says hey i've got 2 comparison statements, ifis used for expressions 1 × 1 === 5where the answer is potentially unknown without computation and switch compares cases in branches, I feel it fits known cases.

When to use switch?

  • do you have multiple things to compare?
  • Is the set of answers known to you.

I'm saying that switch is best for enums, a finite set of know answers. An e what? An enum is like a multiple choice question, you have a finite set of possible answers, all are stored in some sort of object.

const favColour = { answer1: 'red', answer2: 'blue' }
Enter fullscreen mode Exit fullscreen mode

Then later on..

const getAnswer = (userInput) => {
    switch (userInput) {
        case favColour.answer1:
           return "red rocks";
        case favColour.answer2:
           return "blue beloved";
        default
           return `${userInput} is a colour I don't really know or like.`
    }
}

getAnswer("red");
Enter fullscreen mode Exit fullscreen mode

But Adam, default is catching all those unknown answers so that part is infinite? So it's no different to an if statements else. Ahhh I thought you might say that, yes it's true you can use default if you want but notice there is still no expressions, it's all about intent, I know the intention of this block of switch was meant to be finite. If I asked you what your favorite food is and you said airplanes, I know something has gone a bit wrong here.

The above is like a match statement in rust. Anyways it's cool hope you can see the difference between if and switch now.

Top comments (0)