CODE CHALLENGES: JAVASCRIPT FUNDAMENTALS finalGrade()

Hey there folks,

i would very much appreciate any help finding out my faults in following snippet…

it keeps on showing undefined

const finalGrade = (midterm, final, homework) => {

if ((midterm < 0 || midterm > 100) || (final < 0 || final > 100) || (homework < 0 || homework > 100)) {
return ‘You have entered an invalid grade’;
}

let score;
let average = midterm + homework + final / 3;

switch (average) {
case average < 60:
score = ‘F’;
break;
case average < 70:
score = ‘D’;
break;
case average < 80:
score = ‘C’;
break;
case average < 90:
score = ‘B’;
break;
default:
score = ‘A’;
break;
}
return score;
};

I think the problem are the single quotes - try double quotes…

The switch statements you have don’t work correctly.
You have:

switch (average) {
   case average < 60:

average < 60 gives you true or false
so this case checks whether average is true or false,
not whether average is less than 60.

I recommend changing the switch and case stuff to if and else if.

I think you missed a ( and ) :

it should be

let average = (midterm + homework + final) / 3;
2 Likes

thanks of your feedback…

i’ve got it work with if else statements at first. I’d like just to refactor the code into a switch statement… I can’t get it quite right…

const finalGrade = (midterm, final, homework) => {
if ((midterm < 0 || midterm > 100) || (final < 0 || final > 100) || (homework < 0 || homework > 100)) {
return ‘You have entered an invalid grade’;
}
let average = (midterm + homework + final) / 3;
if (average < 60) {
return ‘F’
} else if (average < 70) {
return ‘D’;
} else if (average < 80) {
return ‘C’;
} else if (average < 90) {
return ‘B’;
} else {
return ‘A’;
}
};

thanks for your feedback… the single quotes aren’t the issue here

using a switch statement wouldn’t really be suitable here.
Because switch statements can only check if things are equal, not if something is greater or less.

spoiler:

const finalGrade = (midterm, final, homework) => {
  if ((midterm < 0 || midterm > 100) || (final < 0 || final > 100) || (homework < 0 || homework > 100)) {
    return ‘You have entered an invalid grade’;
  }
  let average = (midterm + homework + final) / 3;
  let dispatch = Math.floor(average / 10);

  switch (dispatch) {
    case 0:
      return 'F';  // break;
    case 1:
      return 'F';  // break;
    case 2:
      return 'F';  // break;
    case 3:
      return 'F';  // break;
    case 4:
      return 'F';  // break;
    case 5:
      return 'F';  // break;
    case 6:
      return 'D';  // break;
    case 7:
      return 'C';  // break;
    case 8:
      return 'B';  // break;
    /*case 9:
      return 'A';  // break;  */
    default:
      return 'A';  // break;
 }
};
1 Like