Sukhpreet Singh Alang
Sukhpreet Singh Alang

Reputation: 37

Sum of numbers in an array with javascript

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>

Upvotes: 3

Views: 619

Answers (5)

Omid Nikrah
Omid Nikrah

Reputation: 2482

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>

Upvotes: 1

Suresh Prajapati
Suresh Prajapati

Reputation: 4467

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

Upvotes: 2

shantanu patwardhan
shantanu patwardhan

Reputation: 31

var sum = [1, 2, 3].reduce(add, 0);
function add(a, b) {
  return a + b;
}
console.log(sum); // 6

Upvotes: 3

Edward Lynch
Edward Lynch

Reputation: 127

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

Upvotes: -1

BenM
BenM

Reputation: 53198

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>

Upvotes: 1

Related Questions