Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Grade book challenge JavaScript
We are required to write a function that finds the mean of the three scores passed to it and returns the letter value associated with that grade according to the following table.
Solution Approach
The function calculates the average of all scores passed as arguments, then uses conditional statements to determine the corresponding letter grade based on the score ranges.
Example
const findGrade = (...scores) => {
const { length } = scores;
const sum = scores.reduce((acc, val) => acc + val);
const score = sum / length;
if (score >= 90 && score <= 100) {
return 'A';
}
else if (score >= 80) {
return 'B';
} else if (score >= 70) {
return 'C';
} else if (score >= 60) {
return 'D';
} else {
return 'F';
}
}
console.log(findGrade(5, 40, 93));
console.log(findGrade(30, 85, 96));
console.log(findGrade(92, 70, 40));
Output
F C D
How It Works
The function uses the rest parameter (...scores) to accept any number of scores. It calculates the sum using reduce(), then divides by the array length to get the average. The if-else chain checks the average against each grade threshold, returning the appropriate letter grade.
Alternative Implementation
Here's a more concise version using a lookup approach:
const findGradeAlternative = (...scores) => {
const average = scores.reduce((sum, score) => sum + score) / scores.length;
if (average >= 90) return 'A';
if (average >= 80) return 'B';
if (average >= 70) return 'C';
if (average >= 60) return 'D';
return 'F';
}
console.log(findGradeAlternative(85, 92, 78)); // Example with B grade
console.log(findGradeAlternative(95, 88, 91)); // Example with A grade
B A
Conclusion
This grade book function efficiently calculates the average of multiple scores and maps it to letter grades using conditional logic. The rest parameter makes it flexible to handle any number of scores.
