Edit: I will leave this post as is, as it may have some value, but please see Archibald’s solution below.
Having a whole long list of ifs and elses is an indication that the code could be improved on — refactored.
The idea is to let the program do the work for you. Looking at your code I can see a pattern.
grade - larger than
15 >=90
13 >=80
11 >=70
9 >=60
7 >=50
5 >=40
3 >=30
1 >=20
Minus 2 for the grade, and minus 10 for the score.
So we could use a loop, and we can count backwards with loops e.g.
// for (start; condition to be met; change to i each time)
for (let i = 90; i >= 20; i -= 10) {
console.log(i); // 90 80 70 60 50 40 30 20
}
That the scores, now for the grades
let currentGrade = 15; // start with the highest
for (let i = 90; i >= 20; i -= 10) {
console.log(i, currentGrade); // (15, 90) (13, 80) ... (1, 20)
currentGrade -= 2; // deduct 2 from grade each time
}
If we add a conditional into that loop we can stop it when it matches a certain score.
let currentGrade = 15; // start with the highest
let gradeAchieved = 0; // a default value
let myScore = 72;
for (let i = 90; i >= 20; i -= 10) {
if (myScore >= i) { // >= 90 >=80 >=70 etc..
gradeAchieved = currentGrade; // 15 13 11 etc
break; // this will break out and stop the loop
}
currentGrade -= 2;
}
console.log(gradeAchieved) // 11
Note: If the score isn’t larger than or equal to 20 we don’t get to assign currentGrade to gradeAchieved, so the gradeAchieved stays at 0.
We can now think about putting that into a function to calculate the grade.
function calculateGrade (score) {
let grade = 15; // starting grade
let gradeAchieved = 0; // a default grade
for ( let i = 90; i >= 20; i-=10 ) {
if (score >= i) {
gradeAchieved = grade;
break;
}
grade -= 2;
}
return gradeAchieved;
}
console.log(calculateGrade(72)) // 11
console.log(calculateGrade(85)) // 13
console.log(calculateGrade(18)) // 0
This can be improved on. Returning from a function e.g. return gradeAchieved
immediately exits the function, which means we can do away with the break statement and gradeAchieved.
function calculateGrade (score) {
let grade = 15;
for ( let i = 90; i >= 20; i-=10 ) {
if (score >= i) {
return grade; // will exit the loop and the function.
}
grade -= 2;
}
// if score was not larger than or equal to 20 then return here instead with 0.
return 0
}
This is just one approach. It does have one noticeable drawback, and that is if the grades change, say you need a score of 85 - 90 to score 13 then it falls apart. In that case similar to windbeneathmywings I would look at some sort of map or array.