Categories
JavaScript Answers

How to use switch on ranges of integers in JavaScript?

Spread the love

Sometimes, we want to use switch on ranges of integers in JavaScript.

In this article, we’ll look at how to use switch on ranges of integers in JavaScript.

How to use switch on ranges of integers in JavaScript?

To use switch on ranges of integers in JavaScript, we use true as the value of switch and add the booleans for the range check in case.

For instance, we write

switch (true) {
  case x < 5:
    alert("less than five");
    break;
  case x < 9:
    alert("between 5 and 8");
    break;
  case x < 12:
    alert("between 9 and 11");
    break;
  default:
    alert("none");
    break;
}

to use switch with true.

And then we add the boolean expressions we want to check for case to do the range checks.

Conclusion

To use switch on ranges of integers in JavaScript, we use true as the value of switch and add the booleans for the range check in case.

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 *