Search code examples
javascriptsyntaxswitch-statement

How to assign a new value in switch case which in a function?


Currently writing a function that converts a numerical grade into American system. Basically the result should be like this:

You got a D (60%)!

But I get this :

You got a 60 60%!

Apart from the brackets what should I do to make it look like as much as possible?

the code is below:

function gradeConverting(grade) {
    let gradePercent = grade + "%";
    switch (grade) {
        case (90 < grade && grade <= 100):
            grade = "A";
            break;
        case (80 < grade && grade <= 89):
            grade = "B";
            break;
        case (70 < grade && grade <= 79):
            grade = "C";
            break;
        case (60 <= grade && grade <= 69):
            grade = "D";
            break;
        case (50 <= grade && grade <= 59):
            grade = "E";
            break;
        case (grade <= 49):
            grade = "F";
            break;
    }
    return console.log("You got a " + grade + " " + gradePercent + "!");
}

gradeConverting(55);

Solution

  • The logic of your code is completely valid but you are using switch() in a wrong way.

    check the doc about : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/switch

    if you put switch(grade) then something in case something is expect a value that match grade instead of an expression that return true|false

    For example:

    switch (grade) {
            case 90: // only for grade === 90
                grade = "A";
                break;
            case 55: // only for grade === 55
            ...
    

    Indeed you can have a function with multiple ifstatement then return lettergrade. Or still use the current logic with some modification and still utilize switch().

    I create another variable for lettergrade, recommend don't modify grade unless you know what you are trying to do.

    function gradeConverting(grade) {
        let gradePercent = grade + "%";
        var lettergrade = ""; 
        switch (true) { // change to true 
            case (90 <= grade && grade <= 100):
            // you want (90 <= grade && grade <= 100) to be evaluated as true in order to execuate
                lettergrade = "A";
                break;
            case (80 <= grade && grade <= 89):
                lettergrade = "B";
                break;
            case (70 <= grade && grade <= 79):
                lettergrade = "C";
                break;
            case (60 <= grade && grade <= 69):
                lettergrade = "D";
                break;
            case (50 <= grade && grade <= 59):
                lettergrade = "E";
                break;
            case (grade <= 49):
                lettergrade = "F";
                break;
        }
        return console.log("You got a " + lettergrade + " (" + gradePercent + ")!");
    }
    
    gradeConverting(100);