What I expect to happen:
I am a first year teacher, and am having trouble explaining to my student the error that is resulting in a NaN console log output…
What actually happens:
Instead of calculating the averages, like intended, it is only returning NaN
The NaN problem can be fixed pretty easily, just change var total to var total = 0 on line 7.
But it has a couple other small issues that prevent it from calculating correctly. This revised function should do the trick:
function calculateAverage(list) {
var total = 0;
for (var i = 0; i < list.length; i++) {
total+=list[i];
}
var avg = total / list.length;
return avg;
}
The combining function can be improved by having it fuse the two lists together and then averaging them:
function combineAverages(arr1, arr2) {
var combinedAvg = calculateAverage(arr1.concat(arr2));
return combinedAvg;
}
And if you’re interested in a different way to average lists, this one will do it without a loop:
function average(arr) {
return Math.round((arr.reduce(function(a, b) {return a+b}) / arr.length));
}