-1

I have this JavaScript code:

var myAge = parseInt ( prompt("Enter your age", 30), 10 );

if (myAge >= 0 && myAge <= 10) {
document.write("myAge is between 0 and 10 <br>");
}

if (!(myAge >= 0 && myAge <= 10)) {
document.write("myAge is NOT between 0 and 10<br>");
}

if (myAge >= 80 || myAge <= 10) {
document.write("myAge is 80 or above OR 10 or below<br>");
}

if ( (myAge >= 30 && myAge <= 39) || (myAge >= 80 && myAge <= 89) ) {
document.write("myAge is between 30 and 39 or myAge is " + "between 80 and 89");
}

I am tasked with converting this into a switch statement. I tried to do that and I came up with this code, but when I enter the number into the prompt, the text doesn't show up:

var myAge = parseInt ( prompt("Enter your age", 30), 10 );

switch(myAge) {

case myAge >= 0 && myAge <= 10 :
document.write("myAge is between 0 and 10 <br>");
break;

case !(myAge >= 0 && myAge <= 10) : 
document.write("myAge is NOT between 0 and 10<br>");
break;

case myAge >= 80 || myAge <= 10 :
document.write("myAge is 80 or above OR 10 or below<br>");
break;

case  (myAge >= 30 && myAge <= 39) || (myAge >= 80 && myAge <= 89) : 
document.write("myAge is between 30 and 39 or myAge is " + "between 80 and 
89");
break;

}

Is it something to do with where my break; things are?

  • 1
    Switches aren't meant to work this way. MyAge is being compared to each case. If statements are best in this regard. If you're hellbent on switches, use switch(true) then do your comparisons throughout. – clearshot66 Oct 23 '18 at 19:38
  • Only if you want to make a case for each possible age. You can let them fall through but still have to make a case for each. You won't really gain anything from it. – nurdyguy Oct 23 '18 at 19:39
  • Possible duplicate of [javascript: using a condition in switch case](https://stackoverflow.com/questions/5464362/javascript-using-a-condition-in-switch-case) – seebiscuit Oct 23 '18 at 19:45
  • Here in your code there is some nested statments and while switch case have break for each case so some of your statment give positive comparisons but don’t reach try to redesign your code and use nested switch case – Osama Oct 23 '18 at 19:48

1 Answers1

0

Switches really aren't meant to work this way.

If you're hellbent on using a switch, you can do it using switch(true) instead:

var myAge = parseInt ( prompt("Enter your age", 30), 10 );

switch(true) {


   *
   *
   *

}
clearshot66
  • 2,292
  • 1
  • 8
  • 17