-1

am trying to make an output of grades using switch but there is an error idk why it didn't work it shows me the default message i checked : and break but i still dont know the error so i need some help thanks

<script>
    var grade=0;
    
    grade=window.prompt("Enter your grade");
    
    switch(grade)
        {
             case grade>= 95:
                document.write("You got A+");
                break;
                
            case grade<95 && grade>= 90:
                document.write("You got A");
                break;   
            
            case grade<90 && grade>=85:
                document.write("You got A-");
                break;
                
            case grade<85 && grade>=80:
                document.write("You got B+");
                break;
                
            case grade<80 && grade>=75:
                document.write("You got B");
                break;
            
            case grade<75 && grade>=70:
                document.write("You got B-");
                break;
                
            case grade<70 && grade>=65:
                document.write("You got C+");
                break;
                
            case grade<65 && grade>=60:
                document.write("You got C");
                break;
                
            case grade<60 && grade>=55:
                document.write("You got C-");
                break;
                
            case grade<55 && grade>=50:
                document.write("You got D");
                break;
                
            case grade<50:
                document.write("You FAILED");  
                break;
                
             default:
                document.write("Wrong Number"); 
        }
</script>

message and i need some help thanks

  • 4
    Does this answer your question? [How can I use ranges in a switch case statement using JavaScript?](https://stackoverflow.com/questions/17145723/how-can-i-use-ranges-in-a-switch-case-statement-using-javascript) – Ivar Apr 15 '20 at 07:25

2 Answers2

0

I tried to make the same code but changed

switch (grade)

to

switch (true)

and it worked

0

What the switch does is, finds what is the exact match. When you use switch(grade), this finds the exact match of 'grade' all the way, as it fails, it goes to default.

If you want to use switch(grade), you need to write all the values to cases.

Why switch(true) works?
It matches which condition is true then gets the result.

lejlun
  • 4,140
  • 2
  • 15
  • 31