0

Switch statement in Js always keeps giving me the last option, please help rectify the proplem

<! doctype html> <html> <head> <script type="text/javascript"></script> </head> <body> <script> var grade=prompt("what is your grade"); alert(grade); switch(grade){ case grade>=90:document.write("<b>excellent</b>"); break; case grade>=80:document.write("<b>very good</b>"); break; case grade>=70:document.write("<b>good</b>"); break; case grade>=40:document.write("<b>fair</b>"); break; default:document.write("<b>failed</b>"); } </script> </body> </html

9th Mar 2020, 12:20 PM
OWINO ALFRED
OWINO ALFRED - avatar
2 odpowiedzi
+ 2
We use switch to replace if else ladder but you have kind of tried to do both. All the cases should be a finite value or a string and not a condition in order for your code to run. https://www.sololearn.com/learn/JavaScript/1139/
9th Mar 2020, 1:37 PM
Avinesh
Avinesh - avatar
0
Hi! the case value must be unambiguous, since the condition is checked for strict equality. you have two choices: either use a check for each value, like this: var grade = prompt("what is your grade")); alert(grade); switch(grade){ case 90: case 91: case 92: case 93: case 94: case 95: case 96: case 97: case 98: case 99: document.write("<b>excellent</b>"); break; .... or use the IF construct
9th Mar 2020, 2:04 PM
Yaroslav Vernigora
Yaroslav Vernigora - avatar