javascript variable initialization shows NaN

Viewed 5937
function sumArray(numbers){
  var sum;
  for(var i in numbers){
      sum += numbers[i];
  }
  return sum;
}

console.log(sumArray([1,2,3,4,5]));

Hi all,

The outcome is NaN. However, if I initialize sum with sum = 0, the outcome is 15. Why JS does not recognize the value type in the array and do the initialization for me? Why does it return NaN in the first case?

Thanks

4 Answers
Related