2

I am trying to get the sum of all the numbers in an array. I am trying to do it in the most simple way but the sum display NAN. why is this so? please help

var numbers = [45, 34, 12, 10, 8, 9];
var i;

for(i=0 ; i<numbers.length; i++){
  var sum = sum + numbers[i];
  //alert(sum);
}
document.getElementById("demo").innerHTML="The sum is" + sum;
<h2>JavaScript</h2>
<p>This example finds the sum of all numbers in an array:</p>
<p id="demo"></p>
Mohammad
  • 20,339
  • 15
  • 51
  • 79

5 Answers5

2

You are creating a new sum variable for each loop iteration, also you are using it before it's declared hence undefined + <some numer> giving you NaN

var total = 0;
[45, 34, 12, 10, 8, 9].forEach(num => {total += num});

document.getElementById("demo").innerHTML=`The sum is: ${total}`;
<h2>JavaScript</h2>
<p>This example finds the sum of all numbers in an array:</p>
<p id="demo"></p>

Also, nice hack with for loop:

var total = 0;
var numbers = [45, 34, 12, 10, 8, 9];
for (var i = 0; i < numbers.length; total += numbers[i++]);

console.log('total', total);
Suresh Prajapati
  • 3,510
  • 4
  • 25
  • 37
2

var sum = [1, 2, 3].reduce(add, 0);
function add(a, b) {
  return a + b;
}
console.log(sum); // 6
Mohammad
  • 20,339
  • 15
  • 51
  • 79
  • 2
    This is just a reduced copy of this [SO](https://stackoverflow.com/questions/1230233/how-to-find-the-sum-of-an-array-of-numbers) question. – Jeroen Heier Oct 07 '18 at 08:54
1

The problem is that you're declaring the sum variable inside the loop and you don't initialize it.

So you get undefined + numbers[i] which equals NaN.

var numbers = [45, 34, 12, 10, 8, 9];
var i;
var sum = 0;

for(i=0 ; i<numbers.length; i++){
sum = sum + numbers[i];
}

document.getElementById("demo").innerHTML="The sum is" + sum;
<p id="demo"></p>
Oram
  • 1,500
  • 2
  • 18
  • 22
Omid Nikrah
  • 2,307
  • 3
  • 12
  • 27
1

The problem is that sum is defined outside the scope of your function, so what you're actually doing is var sum = undefined + numbers[i] (which is NaN).

Even then, it is better to use either reduce or arrow functions (if you can use ES6).

Using reduce():

var numbers = [45, 34, 12, 10, 8, 9],
    sum     = numbers.reduce(function(a, b) { return a + b; }, 0);
    
document.getElementById('output').innerHTML = sum;
<div id="output"></div>

Using arrow functions:

var numbers = [45, 34, 12, 10, 8, 9],
    sum     = numbers.reduce((a, b) => a + b, 0);
    
document.getElementById('output').innerHTML = sum;
<div id="output"></div>
BenM
  • 51,470
  • 24
  • 115
  • 164
-1

You're instantiating sum each time, take var sum out the loop and jut have sum.

Also you could use Array.prototype.reduce: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce

Edward Lynch
  • 148
  • 8