4

I use this code to enter a number and compare it using less and greater than within switch case how should I do to get the correct result, only default can works

var sum=prompt("enter sum:");

// sum=50;
switch(sum)
{
case sum=0:
  alert("sucess");
  break;
case sum>50:
  alert("also sucess");
  break;
case sum<50:
  alert("failed");
default:
 alert("there is errorrrr");

}
ilkerkaran
  • 4,214
  • 3
  • 27
  • 42
Dina
  • 43
  • 1
  • 3
  • 2
    first case should be `case sum == 0:` And 50 goes to default since none of conditions not met – ilkerkaran Apr 12 '19 at 13:08
  • 1
    @Progressive Actually it's [generally considered better](https://stackoverflow.com/questions/359494/which-equals-operator-vs-should-be-used-in-javascript-comparisons) if it's `case sum === 0:` – nicholaswmin Apr 12 '19 at 13:09
  • @NikKyriakides you are absolutely right. Old habits (c# guy here) die hard =) – ilkerkaran Apr 12 '19 at 13:12

3 Answers3

3

You can use switch (true):

switch (true) {
  case sum === 0:
    alert('success');
    break;
  case sum < 50:
    alert('also success');
    break;
  case sum > 50:
    alert('failed');
    break;
  default:
    alert('there is an error.')
    break;
}

Note that in your code, the first case is actually an assignment and modify sum to set it to 0.

Étienne Miret
  • 6,448
  • 5
  • 24
  • 36
  • 1
    also worth noting that the return value of a `prompt` is a string. conversion will have to happen for the comparisons to have meaningful results. – rlemon Apr 12 '19 at 13:13
-1

It actually doesn't work, as you expect, the switch statement is compared against all cases, such as :

switch (something)
{
    case 1: // something == 1 ?
    // ....
}

Actually, what you have write was interpreted such as

var sum = 42;
switch(sum)
{
    case sum < 50: // sum == sum < 50 ? -> 42 == 42 < 50 ? -> 42 == true ? false !
    // ...

Instead, you can use a switch true statement.

//        v-------     convert the prompt to a numeric value
let sum = + prompt("enter sum:");

switch(true)
{
//         VV----- notice the double equal
  case sum == 0:       // true == sum == 0 ? 
    alert("sucess");
    break;
  case sum > 50:
    alert("also sucess");
    break;
  case sum < 50:
    alert("failed");
    break;     //  <---- You forgot a break; there
  default:
    alert("there is errorrrr");
    break;
}
Cid
  • 14,968
  • 4
  • 30
  • 45
-1

ur idea works fine

sum=20;
switch(true)
{
case 50:
  alert("sucess");
  break;
case (sum>50):
  alert("also sucess");
  break;
case sum<50:
  alert("failed");
 break;        
default:
 alert("there is errorrrr");

}
jasinth premkumar
  • 1,430
  • 1
  • 12
  • 22