Review JavaScript Fundamentals by Building a Gradebook App - Step 1

Tell us what’s happening:

I’m getting results but not the average. I have tried many variations an still not correct. I’m getting 92 and 45. I am not clear on how to get the average. How should I formulate the equation? I’m lost. Here is my code:

function getAverage(scores) {
 for(let i = 0; i < scores.length; i++) {
   let sum = 0;
    sum += scores[i];
   return sum;
 }
}

Your code so far


// User Editable Region


function getAverage(scores) {
 for(let i = 0; i < scores.length; i++) {
   let sum = 0;
    sum += scores[i];
   return sum;
 }
}

console.log(getAverage([92, 88, 12, 77, 57, 100, 67, 38, 97, 89]));
console.log(getAverage([45, 87, 98, 100, 86, 94, 67, 88, 94, 95]));

// User Editable Region

Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/129.0.0.0 Safari/537.36

Challenge Information:

Review JavaScript Fundamentals by Building a Gradebook App - Step 1

You’re doing just fine, The problem is the placement of your sum variable, the return statement and how you calculated the average.

1 . Move the sum variable so that it’s in the function block, doing so will increase its visibility/scope, right now it’s limited to a block scope.
2. Since you’re returning the sum inside the loop, your function will exit after the first iteration, it needs to be within the function for all iterations to count.
3. Finally, you’re provided with an example formula for calculating the average.

average = sum of all scores / total number of scores

You’re missing the second part of the formula. scores.length is equivalent to the length of the iterable; in this case, an array.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.