Review JavaScript Fundamentals by Building a Gradebook App - Step 1

Tell us what’s happening:

I’ve used a for loop to get the sum of the array and the function to divide it by the length of the array and it works fine the first time the function is called, but for some reason the second time the function is called it ads the average of the second array onto the first one.
thank you in advance for your help!
p.s. I tried to google search it but was a bit stuck shortening the qestion, if you have any advice on that i’d appreciate it.

Your code so far


// User Editable Region

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

  }
  return num / 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/125.0.0.0 Safari/537.36

Challenge Information:

Review JavaScript Fundamentals by Building a Gradebook App - Step 1

This global variable is breaking the functionality

Thank you, that worked great!
I contiuned experimenting, and i can’t figure out why the folowing solution dosn’t work

function getAverage(scores) {
  let num = 0;
  for (let score of scores) {
num += score.pop
  }

}

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]));

Also I would appreaciate an answer on how to google search compex issues.
I also apologize for any spelling mistakes
Thank you for the help

what is pop? Does a number have a property?

1 Like

I thought pop would pass the last and therefore most recent variable added to the array and add it to num

Hi @theadore

The .pop() method may not work with this type of loop.

Happy coding

Why not?
To make my post long enough I’ll take the oppertunity to say thank you again

Each time the last element is removed, the length of the array is shortened.

A for ... of loop will start out with a certain length.
.pop() will alter the length of the array, then the loop will run out of elements to iterate over as they were removed.
So the loop may not iterate over all the elements.

Happy coding

what are the values of score?

I had thought that each time the loop runs, one of the items in the scores array is added to score. Is this not true?

What do you mean by “added to”? I don’t think score is what you think it is. Try console.loging the value of score inside of the loop.