0

Good afternoon! Why does the first option work - switch (true), and the second option does not work - switch (a)?

First:

var a= prompt('Enter value', '');
switch(true)
{
    case a>10:
        alert('a>10');
    break;

    case a<10:
        alert('a<10');
    break;

    default:
        alert('a===10');

Second:

var a= prompt('Enter value', '');
switch(a)
{
    case a>10:
        alert('a>10');
    break;

    case a<10:
        alert('a<10');
    break;

    default:
        alert('a===10');
julianstark999
  • 3,450
  • 1
  • 27
  • 41

4 Answers4

4

Why does the first option work - switch (true), and the second option does not work - switch (a)?

As per documentation

The switch statement evaluates an expression, matching the expression's value to a case clause, and executes statements associated with that case.

So, in your first option true will match to either a < 10 or a > 10, however in second option, a being a string may not match to either of them.

gurvinder372
  • 66,980
  • 10
  • 72
  • 94
2

Edit: I just realize OP ask for the difference instead of why it won't work, sorry for misunderstanding the question


It should work nicely

var a = prompt('Enter value', '');

switch (true) {
    case (a > 10):
        alert("a > 10");
        break;

    case (a < 10):
        alert("a < 10");
        break;

    default:
        alert('a == 10');
}
AngYC
  • 3,051
  • 6
  • 20
0

It's because a > 10 is true, like the switch(true), while switch(a) was passed a, which is not true. Of course, you should cast a. a = +a or use parseInt() or parseFloat().

Here's what you probably meant to do:

var a = prompt('Enter value');
if(+a > 10){
  alert('a > 10');
}
else if(a !== '' && +a < 10){
  alert('a < 10');
}
else if(+a === 10){
  alert('a === 10'); 
}
else{
  alert('Really, you should avoid using prompt and alert!');
}
// notice this is less code than that pointless switch
  
StackSlave
  • 10,613
  • 2
  • 18
  • 35
-2

You need to convert the user input from a string to an integer, like so

a = parseInt(a)
newman
  • 424
  • 2
  • 12