FAQ: Code Challenges: JavaScript Fundamentals - finalGrade()

It’s a logical progression (process of elimination). Study it closely to see what I mean by that.

1 Like

Hi guys, my code is working but I’m thinking of how to reduce it! Especially this part: grade1 < 100 && grade2 > 0 && grade2 < 100 && grade3 > 0 && grade3 < 100
Is it possible to define it first so it doesn’t need to be repeated?

Thanks for the help!

const finalGrade = (grade1, grade2, grade3) => {

const average = ((grade1 + grade2 + grade3) / 3);

if (average >= 0 && average <= 59 && grade1 > 0 && grade1 < 100 && grade2 > 0 && grade2 < 100 && grade3 > 0 && grade3 < 100) {
return ‘F’;

} else if (average >= 60 && average <= 69 && grade1 > 0 && grade1 < 100 && grade2 > 0 && grade2 < 100 && grade3 > 0 && grade3 < 100) {
return ‘D’;

} else if (average >= 70 && average <=79 && grade1 > 0 && grade1 < 100 && grade2 > 0 && grade2 < 100 && grade3 > 0 && grade3 < 100) {
return ‘C’;

} else if (average >=80 && average <= 89 && grade1 > 0 && grade1 < 100 && grade2 > 0 && grade2 < 100 && grade3 > 0 && grade3 < 100) {
return ‘B’;

} else if (average >= 90 && average <=100 && grade1 > 0 && grade1 < 100 && grade2 > 0 && grade2 < 100 && grade3 > 0 && grade3 < 100) {
return ‘A’;
} else
{
return ‘You have entered an invalid grade.’;
}
}

Validate first, then compute the average, then assign a letter grade. Since there are three values that must be validated, it will take some logic.

if (grade1 < 0 || grade1 > 100 || grade2 < 0 ...) {
    return "You have ..."
}
// compute average
//  assign letter grade and return
1 Like