This page looks best with JavaScript enabled

Using switch with number ranges

 ·   ·  ☕ 1 min read

You can easily use switch to check whether a number is in specified range.

We have seen the advantages of using switch instead of if/else.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
const num = 1;
switch (num) {
  case 1:
    console.log("one");
    break;
  case 2:
    console.log("two");
    break;
  case 5:
    console.log("five");
    break;
  default:
    console.log("none");
}

You are sold by now, but there is this problem - how will you use switch if you need to check whether num < 10 and num > 5.

You may have missed this from our date validation logic, but switch can do the range checks well. You just have to change the conditions a bit.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
const num = 6;
switch (true) {
  case num == 1:
    console.log("one");
    break;
  case num == 2:
    console.log("two");
    break;
  case num > 5 && num < 10:
    console.log("five to ten");
    break;
  default:
    console.log("none");
}
Stay in touch!
Share on

Prashanth Krishnamurthy
WRITTEN BY
Prashanth Krishnamurthy
Technologist | Creator of Things