Using switch case with conditionals - returning only one expected response

You must select a tag to post in this category. Please find the tag relating to the section of the course you are on E.g. loops, learn-compatibility

When you ask a question, don’t forget to include a link to the exercise or project you’re dealing with!

If you want to have the best chances of getting a useful answer quickly, make sure you follow our guidelines about how to ask a good question. That way you’ll be helping everyone – helping people to answer your question and helping others who are stuck to find the question and answer! :slight_smile:

function numberDigits(x) { switch (x) { case x >= 0 & x <= 9 : return `One digit: ${x}`; break; case x >=10 & x <= 99 : return `Two digits: ${x}`; break; default : return `The number is: ${x}`; break; }; }; console.log(numberDigits(245)); console.log(numberDigits(15)); console.log(numberDigits(1)); console.log(numberDigits(-15));

I would love some help understanding why this code returns the expected response only in the instance where x = 1. I have tried various forms of syntax within this switch statement including separating each side of my case conditionals with parentheses [e.g. (x >= 0) && (x <= 99)], using && and ||, not using a default but instead using a third case (x <0 || x > 99) - and even a third and fourth case where x < 0 and then x > 99. I’m at a loss here. I know I could change this to an if statement and probably get the correct answer, but I want to know why only part of this code block is running as expected. Help, please!

This is the specific lesson: JavaScript Practice: Data Types, Conditional, Functions

Thanks in advance.

1 Like

Hi there!

Simple answer is, switch statements don’t do that. They can’t handle any complicated conditionals like that. They can only check x===y things.

If you want compounded conditionals like that, you need to use if statements.

3 Likes

Thank you. I did end up changing it to an if…else statement and was able to get the expected responses. I’m still really curious as to why this worked in that one instance, though. Maybe I’ll understand what happened as I dig further into Javascript.

Thanks again.

1 Like

In short, because of the default.

On a switch clause, the optional default clause does this:

A default clause; if provided, this clause is executed if the value of expression doesn’t match any of the case clauses.

Further reading about this.

In your code, you have this default clause:

default : return `The number is: ${x}`;

So that is what is returned every time if the expression doesn’t match any of the other (previously indicated) cases.

1 Like

In good practise, they can’t, but you can get them to if you use:

switch (true) {
//now you can have things like:
case someVar === anotherVar:
  //code
}