Facing Error in validation

let grades = {
F : 60,
D : 70,
C : 80,
B : 90,
A : 100
}

function getGrade(s1, s2, s3){
let total = (s1 + s2 + s3) / 3
for( let g in grades){
if(total <= grades[g]){
return g
}
}
}
getGrade(70, 70, 100)

am messing up with an error like am checking that total is less than grades[g]. when i call this function using these parameters its total is 80 but it’s not stopping its evalution at c it’ll continue to B and it stops. why this is happening guys

1 Like

I just copied your code and executed in repl the output id ‘C’ as expected I don’t see any error


so this is the screenshot of the output and link of the repl

1 Like

@Ganesh the error is simple yet hard to notice.
Problem is in your logic inside if condition.
“total<=grades[g]” will give you all the grades that are greater than your total i.e. 80.
But even if you keep “total>=grades[g]” inside your if condition, that will give you all the grades that are smaller than your total i.e. F, D, C.
I would suggest you to capture the grades in a variable and then finally return that variable.

var grades = {

F: 60,
E: 70,
C: 80,
B: 90,
A: 100
}

// console.log(grades);

function getGrades(s1, s2, s3){
var total = (s1+s2+s3)/3;
var fGrade ;
for(g in grades){
if(total >= grades[g]){
fGrade = g;
}
}
console.log(fGrade);
}

getGrades(70, 70, 100);

Hope this is helpful.