Review javascript fundamentals by building

Hello guys, so i am attempting the building grade book task and this is my code;

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

The answer to the first average log was correct but the second one is not. I realized this is because my sum declaration and initialization is not inside my function code block. I am quite confused about why this won’t make the code work because I know initializing with let makes it a global scope.

who knows why the answer to the first log is correct and the second isn’t based on my realization?

1 Like

Hello,
I did not completely understand your question, but I am assuming you are wondering why in the second log the result included the first log value, if that is the case then it is because you defined the sum variable outside the getAverage function which made it hold the result of the first log, if you want the sum variable to hold just the value of the current log you should move the let sum = 0 line inside the function

hello, thank you for taking the time to respond.

I don’t really understand what you mean by defining the sum variable outside the getAverage function made it hold the result of my first log… the answer of the second log is simply *2 of the first log and I didn’t specify a multiplication anywhere in my function.

please could you explain better. thanks so much

This sum is outside of your function. This is generally a bad idea because the same sum keeps getting added to every single time you use the function instead of using a new sum for every function call

thank you for the clarification!