Refactor a Function to Calculate Average Scores with Better Readability and Efficiency
Improve a messy JavaScript function that calculates average scores from an array of student objects, making the code cleaner, more efficient, and easier to understand without changing its behavior.
Challenge prompt
You are given a function that calculates the average score of students from an array of student objects. The function works correctly but is hard to read, contains redundant operations, and could be optimized. Refactor the function to improve readability, remove unnecessary steps, and maintain the same output behavior. Do not change the function signature or the way it receives input.
Guidance
- • Focus on simplifying loops and conditionals.
- • Use built-in array methods where appropriate to improve clarity.
- • Ensure the function handles empty input arrays gracefully.
Hints
- • Consider using Array.prototype.reduce to aggregate total scores.
- • Avoid recalculating constants or repeatedly parsing the same data.
- • Use meaningful variable names and remove unused variables.
Starter code
function calculateAverage(students) {
let total = 0;
let count = 0;
for (let i = 0; i < students.length; i++) {
if (students[i].score != null) {
total += Number(students[i].score);
count++;
}
}
if (count === 0) {
return 0;
}
let average = total / count;
return average.toFixed(2) * 1; // Convert string to number
}Expected output
calculateAverage([{name: 'Alice', score: 85}, {name: 'Bob', score: 90}, {name: 'Carol', score: 95}]) // 90
Core concepts
Challenge a Friend
Send this duel to someone else and see if they can solve it.