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

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.

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:

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.


Thank you very much!

1 Like

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

hi, would you be able to provide an example for a switch statement to find if an integer x is greater than or less than 50
, and print “greater than” or " less than" for the input?

let x = 50;
let y;
switch (true) {
case x > 50: y = 'greater than'; break;
case x < 50: y = 'less than'; break;
default: y = 'equal to'
console.log(`x is ${y} 50.`)

Note that the switch doesn’t care if x is an integer, or not, only that the logic is adequate to the task. Technically, there are no integers in JavaScript, only numbers, as in the Real number set. We call those, ‘floats’.

As a side note, the key to understanding a switch statement is to treat both the parameter and the case arguments as expressions. The mechanics of a switch is simply to match expressions or fall back on the default (or do nothing).

switch (expression) {
case espression1: ...
case expression2: ...
default: ...

Expressions are values, so when the parameter is a value, the case that matches it is the branch followed. true is a value, and an expression. A boolean expression is a value. That’s why the above example works. Both parameter and case argument are boolean and therefore have some likelihood of matching.

On a final note, the example switch has so few cases that we could simplify that logic even further with a ternary expression.

let x = 50
`x is ${x > 50 ? 'greater than' : x < 50 ? 'less than' : 'equal to'} 50`

The only proviso is that we don’t see this as better code, only a different take on this particular logic. Ternaries need to be kept simple or bugs can creep in and readability can be degraded. Make it obvious that you are using one, and make the reasoning obvious, too. Just saying.