javascriptconsole.log

console log results adding to each other, rather than printing separately


I have a function that works, and it gives me the correct return when I only use one consol.log statement. But as soon as I add 2 or more console.log statements when calling my function, it will add the printed return values together rather than print them individually. I do not want this.

Ran the function

let sum = 0;
const scores = [];

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

Which correctly prints the first log statement as 71.7, but instead of printing 85.4 below as my second console.log should, it adds the two together into 157.1. When I comment out the first console.log, then the second log statement works just fine. I am just unsure of what is adding the two return values together when both values are printed at the same time.


Solution

  • You have the sum variable as a global and do not clear it at the start of your function.

    Moving the sum declaration inside the function, fixes the problem.

    function getAverage(scores) {
      let sum = 0;
      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]));