Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

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!');
}