Review JavaScript Fundamentals by Building a Gradebook App - Step 1

Tell us what’s happening:

//let scores = [92, 88, 12, 77, 57, 100, 67, 38, 97, 89];
let sum = 0;

function getAverage(scores) {
for (let i = 0; i < scores.length; i++) {
sum += scores[i];
}
let average = sum / scores.length;
return average;
}

console.log()
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]));//

why is my code taking the sum of the first getavg, adding it to the second, and spitting out the average of both?

Your code so far


// User Editable Region

let scores = [92, 88, 12, 77, 57, 100, 67, 38, 97, 89];
let sum = 0;


function getAverage(scores) {
  for (let i = 0; i < scores.length; i++) {
     sum += scores[i];
  }
  let average = sum / scores.length;
  return average;
}

console.log()
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/135.0.0.0 Safari/537.36

Challenge Information:

Review JavaScript Fundamentals by Building a Gradebook App - Step 1

Why is sum ’ global variable?

Good job in noticing that!

Your code contains global variables that are changed each time the function is run. This means that after each function call completes, subsequent function calls start with the previous value. To fix this, make sure your function doesn’t change any global variables, and declare/assign variables within the function if they need to be changed.

Example:

var myGlobal = [1];
function returnGlobal(arg) {
  myGlobal.push(arg);
  return myGlobal;
} // unreliable - array gets longer each time the function is run

function returnLocal(arg) {
  var myLocal = [1];
  myLocal.push(arg);
  return myLocal;
} // reliable - always returns an array of length 2