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!
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."
);
You need switch(true) and the rest stays the same (I guess).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With