Review JavaScript Fundamentals by Building a Gradebook App - Step 1

Tell us what’s happening:

Building a Gradebook App 1

let sum=0;
function getAverage (scores){
// brings up the scores so i could see them
console.log(scores);
console.log(scores.length);
//then i did a for loop
for(let i = 0 ; i < scores.length; i++){
//get scores total
sum = sum + scores[i];
}
console.log(sum/scores.length);
}
If i comment out one of the two score arrays i can log out just fine.
But if i don’t comment out one , the sum keeps summing up all the grades in both score arrays.

Your code so far


// User Editable Region

 let sum=0;
function getAverage(scores) {
console.log(scores);
  for(let i=0;i < scores.length;i++){
    sum= sum + scores[i];
    
    
  }
  
  console.log("The average for this scores array"+" "+ sum/scores.length);
  
}
  

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 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36 Edg/128.0.0.0

Challenge Information:

Review JavaScript Fundamentals by Building a Gradebook App - Step 1

don’t write the sum variable in the global scope.
Move it inside the function so it can be reset each time someone calls the function.

Also don’t forget to return something.

1 Like

Thank you . I have been working on this for days i even put a if statement to set the sum to 0 if i= scores.length-1

1 Like

probably that didn’t work? The variable i gets reset each time the loop code is encountered for the first time. (each function call)

1 Like

no i could set sum to 0 but i just couldn’t get the output to log correctly
loged out the first ave and the second below the second score area.
any how . moving the let sum= 0 did rest the sum now i will try to use a return to log out the scores correctly. Thanks again.

Thanks all is good .

What am i doing wrong here?
let scores = ;
function getAverage(scores) {
let sum = 0;
let average = 0;
for (let i = 0; i <= scores.lenght; i++){
sum = sum + scores[i];
}
average = sum / scores.lenght;
return average
}
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]));

it keep returning NaN as a result

If you have a question about a specific challenge as it relates to your written code for that challenge and need some help, click the Help button located on the challenge. This button only appears if you have tried to submit an answer at least three times.

The Help button will create a new topic with all code you have written and include a link to the challenge also. You will still be able to ask any questions in the post before submitting it to the forum.

Thank you.