The challenge
Write average(scores) that returns the average of an array of numbers. Return 0 for an empty array.
Try it
Write your answer below, then press Check my answer. Your code runs right here in your browser, and the tests tell you what works.
It prints
What the tests check
average([80, 90, 100])gives90average([1, 2])gives1.5average([])gives0
Hints
Stuck? Open one hint at a time. Try again after each one.
Hint 1
Add them all up with a loop, then divide by scores.length.
Hint 2
Check for an empty array first, or you’ll divide by zero and get NaN.
A solution
There’s always more than one right way. Read it, make sure you understand it, then try writing it yourself without looking.
Show one possible solution
function average(scores) {
if (scores.length === 0) return 0;
let total = 0;
for (const s of scores) total += s;
return total / scores.length;
}
Learn what you need
This exercise uses what Grade 7: Arrays: Lists of Things teaches. Read those notes first if any of it is new.