Review JavaScript Fundamentals by Building a Gradebook App - Step 1

Tell us what’s happening:

hi. I have been stuck on this first step for a while now and have researched how to code a for loop to return the sum of the grades in our given array. I then went on to use the .length array property to return the avg and still can’t seem to pass the tests. does anyone have advice?

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
}
  let avg = sum / scores.length; 
    return avg;
}

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/605.1.15 (KHTML, like Gecko) Version/17.1 Safari/605.1.15

Challenge Information:

Review JavaScript Fundamentals by Building a Gradebook App - Step 1

You are returning out of the function too early.

  1. Scope the sum variable to the top of the function, not the loop.

  2. Remove return sum and only keep return avg

1 Like

thanks! so I did what you advised me to and got the first avg log to run correctly, returning a value of 71.1. However the second array of numbers logged seems to be returning a value of 157.1 when it is supposed to return a value of 85.4. do you know why this is?

this is my updated code:

let sum = 0;
function getAverage(scores) {
for (let i=0; i < scores.length; i++){
sum += scores[i];
}
let avg = sum / scores.length;
return avg;
}
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]));

Because your sum variable was declared in the global scope and retains the value it had prior.
Move it down into the function.

1 Like

As said, sum should be scoped to the function. That is, it should be declared inside it.

1 Like

Thank you! this worked.