Can you use conditional operators with a switch statement?

I’m practicing using switch statements and wondered whether it is possible to use conditional operators? For example, with an if else statement I could write the following:

let a = 5;

if (a < 5) {
  console.log('Less than 5');
} else if (a === 5) {
  console.log('5');
} else if (a < 10) {
  console.log('Less than 10');
} else if (a === 10) {
  console.log('10');
} else {
  console.log('Greater than 10!');
}

However, when I tried to use a switch statement such as the one below it doesn’t work as I would expect… the code below just prints ‘Greater than 10!’

let a = 5;

switch (a) {
  case a < 5: 
    console.log('Less than 5');
    break;
  case a === 5:
    console.log('5');
    break;
  case a < 10: 
    console.log('Less than 10');
    break;
  case a === 10: 
    console.log('10');
    break;
  default: 
    console.log('Greater than 10!');
}

Switch doesn’t quite work the way you are thinking. When you say, switch(a) {, the first case that matches whatever a is will be executed. That in mind, what if you changed your code to the following?

let a = 5;

switch (true) {
  case a < 5: 
    console.log('Less than 5');
    break;
  case a === 5:
    console.log('5');
    break;
  case a < 10: 
    console.log('Less than 10');
    break;
  case a === 10: 
    console.log('10');
    break;
  default: 
    console.log('Greater than 10!');
}
2 Likes

Ah gotcha! Took me a few minutes to think things over but now I think I understand! Settings the test condition to true will cause the case that evaluates to true to run as they now match.

1 Like

You got it. :slightly_smiling_face: