CJ Johnson CJ Johnson - 4 years ago 310
Javascript Question

Javascript Averages

I am trying to learn Javascript. I've built the following code to find the average from an array of numbers. It works except the last returned value is always NaN. I cannot figure out why. If I move this piece outside of the block it seems to forget altogether what the variable sum is supposed to be equal to. Is there some kind of global-variable type equivalent I'm supposed to be using for JS?

var average = function(myarray) {
sum = 0;
for (counter = 0; counter <= myarray.length; counter++) {
sum = sum + myarray[counter];
average = sum / myarray.length;
console.log(average);
};
}

average([1, 2, 3])

Answer Source

Change

counter <= myarray.length

to

counter < myarray.length

because indexes start at 0.

Full example:

var average = function(myarray) {
  var sum = 0;
  for (var counter = 0; counter < myarray.length; counter++) {
    sum += myarray[counter];
   }

   return sum / myarray.length;
}

console.log(average([1,2,3]));

JSBin Demo: http://jsbin.com/siyugi/1/edit

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download