Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript switch-case using a condition

I just started learning JavaScript and I have a really basic knowledge of C#.

Tried running this piece of code:

var number = parseInt(prompt("Enter a number:"));

switch (number) {
  case number >= 1 && number <= 9:
    alert("The number " + number + " is a single digit number.");
    break;
  case number >= 10 && number <= 99:
    alert("The number " + number + " is a two digit number.");
    break;
  case number >= 100 && number <= 999:
    alert("The number " + number + " is a three digit number.");
    break;
  case number >= 1000 && number <= 9999:
    alert("The number " + number + " is a four digit number.");
    break;
  default:
    alert("Your number has 5 or more digits.");
}

but it kept failing after the following:

number <= 9

Can you guys please give me a hand here?

Thanks a lot!

like image 961
GalSab Avatar asked Jan 12 '23 19:01

GalSab


2 Answers

The switch statement does compare its argument with the values of the expressions in the cases.

In your code, it does compare the number with those boolean results from the cases, so it only gets in the first case when your number is 1 (because 1 == true) and falls to the default otherwise. You could simply compare them to true, like

switch (true) {
  case number >= 1 && number <= 9:
    alert("The number " + number + " is a single digit number.");
    break;
  case number >= 10 && number <= 99:
    alert("The number " + number + " is a two digit number.");
    break;
  case number >= 100 && number <= 999:
    alert("The number " + number + " is a three digit number.");
    break;
  case number >= 1000 && number <= 9999:
    alert("The number " + number + " is a four digit number.");
    break;
  default:
    alert("Your number has 5 or more digits.");
}

but it would be cleaner to use an if-else construct:

if (number >= 1 && number <= 9)
  alert("The number " + number + " is a single digit number.");
else if (number >= 10 && number <= 99)
  alert("The number " + number + " is a two digit number.");
else if (number >= 100 && number <= 999)
  alert("The number " + number + " is a three digit number.");
else if (number >= 1000 && number <= 9999)
  alert("The number " + number + " is a four digit number.");
else 
  alert("Your number has 5 or more digits.");

Btw, much shorter would be

var l = String(number).length;
alert(l<5
   ? "The number "+number+" is a "+[,"single","two","three","four"][number]+" digit number."
   : "Your number has 5 or more digits."
);
like image 160
Bergi Avatar answered Jan 15 '23 09:01

Bergi


You need switch(true) and the rest stays the same (I guess).

like image 27
kul_mi Avatar answered Jan 15 '23 08:01

kul_mi