Can I use greater than/less than for a switch statement?


#1

Like for example if a variable is less than a specific number, let’s say less than 4. The program will print out cases 1 to 3.


#2

switch works in two ways, one way is to match an expression to a value, the other is to match a value to an expression.

var value = 5
switch (value) {
    case 1:
    case 2:
    case 3:
    case 4:
    case 5:
    default:
}

In the above, value is the expression.

switch (true) {
    case value < 4:
    case value > 4:
    default: // value is 4
}

These examples are bit vague but a quick experiment will help to demonstrate them.


#3

Thank you very much!


#4

You’re very welcome.

Here’s another example…

num = Math.floor(Math.random() * 100 + 1)
switch(0) {
    case num % 15:     // fizzbuzz
    case num % 3:      // fizz
    case num % 5:      // buzz
    default:           // num is not fizz or buzz
}