Categories
JavaScript Answers

How to use ranges in a switch case statement using JavaScript?

Spread the love

Sometimes, we want to use ranges in a switch case statement using JavaScript.

In this article, we’ll look at how to use ranges in a switch case statement using JavaScript.

How to use ranges in a switch case statement using JavaScript?

To use ranges in a switch case statement using JavaScript, we use switch with true.

For instance, we write

switch (true) {
  case myInterval < 0:
    break;
  case myInterval >= 0 && myInterval <= 2:
    doStuffWithFirstRange();
    break;
  case myInterval >= 3 && myInterval <= 5:
    doStuffWithSecondRange();
    break;
  case myInterval >= 6 && myInterval <= 7:
    doStuffWithThirdRange();
    break;
  default:
    doStuffWithAllOthers();
}

to use switch with true.

Then we check the value of myInterval with the ranges the case expressions.

Conclusion

To use ranges in a switch case statement using JavaScript, we use switch with true.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *