Hi, the code that I have written works but how do I get it to pass both tests at the same time? When I test each set of scores it works fine but I don’t know how to get both sets of scores to go throught console.log separately…
Your code so far
// User Editable Region
let sum = 0
let scores = [92, 88, 12, 77, 57, 100, 67, 38, 97, 89]
function getAverage(scores) {
if (scores.length > 0) {
return sum / scores.length;
} else {
return 0.0;
}
}
for (let i = 0; i < scores.length; i++){
sum+=scores[i]
}
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/125.0.0.0 Safari/537.36
Challenge Information:
Review JavaScript Fundamentals by Building a Gradebook App - Step 1
A bit more advice:
as well as removing your declared array, initialize variable ‘sum’ inside function as the first line and place the for loop inside function before the return statement - no need to allow for there being no values in array (not really asked for).
Thanks, it’s interesting that once I moved the let sum = 0 into the function as the first line the code ran properly giving results of 71.7, 85.4 , but when I had let sum = 0 stay as a global variable it gives the results 71.7, 157.1
Because sum is just accumulating the values each time the function gets called since it was initialized to zero —outside— the function in the global scope. You could as a test, leave it in the global scope then add this line
sum=0;
in the first line of the function and that will reset it back to zero.
However it is bad coding practice to declare global variables unless necessary (which is not the case here).