13

I need to sum all my numbers from a for loop with javascript

var nums = ['100','300','400','60','40'];

for(var i=1; i < nums.length; i++){

        var num = nums[i] + nums[i];

        alert(num);
}​

can someone help http://jsfiddle.net/GYpd2/1/

the outcome i am looking for is 900

1
  • 1
    What you are currently doing is concatenating each string with itself and assigning the result to num. I recommend to read the MDN JavaScript Guide to learn the basics. Commented Jul 27, 2012 at 11:21

14 Answers 14

29
var nums = ['100','300','400','60','40'];
var sum = 0;

for(var i=0; i < nums.length; i++){

    sum += parseInt(nums[i]);

}

alert(sum);

Tested: http://jsfiddle.net/GYpd2/6/ (thanks to user1503606)

If nums contains numbers only there is no need for parseInt().

0
8

Prime example for ES5's Array.prototype.reduce method. Like:

var nums  = ['100','300','400','60','40'];

var total = nums.reduce(function(a,b) {
    return (+a)+(+b);
});

Demo: http://jsfiddle.net/FwfmE/

5
var nums = ['100','300','400','60','40'], 
    num = 0;

for (var i = 0; i < nums.length; i++) {
    num += +nums[i];
}
alert(num);
​
3
  • @SnowBlind, Are you kidding? :) Commented Jul 27, 2012 at 11:28
  • Sorry, my bad.. But what is the meaning of + on the left of nums[i]; ?
    – Snow Blind
    Commented Jul 27, 2012 at 11:32
  • 1
    This is unary operator, it uses to convert string to integer Commented Jul 27, 2012 at 11:34
4

Do it like this

var nums = ['100','300','400','60','40'];
var total = 0;    

for(var i=0; i < nums.length; i++){
    total = total + Number(nums[i]);
}
alert(total);
  1. The loop starts with 0 not 1.

  2. total variable needs to be declared before the loop or else it will not preserve the previous addition.

  3. Use Number() to convert string to number.

  4. Adding string means concatitation '100' + '200' will give '100200'.

3
var num, nums = [100,300,400,60,40];

for ( var i=1; i < nums.length; i++ ) {
    num += nums[i];
}​

alert(num);
2

If you have a reduce function , you can just do this:

var nums = ['100','300','400','60','40'],
    sum = nums.reduce(function(accum, val) {return accum + Number(val);}, 0);
alert(sum);
2
var nums = ['100','300','400','60','40'];
var num = 0; 

for(var i=0; i < nums.length; i++){
    num = parseInt(num) + parseInt(nums[i]);
}

This is how I did it. It's very similar to other's code, but a different way of writing it. You do need to start your initial i value in your for loop with 0.

1
  • Great! This is the only solution that is working here.
    – Courage
    Commented Jun 6, 2023 at 8:43
1

Here is JSFiddle

and code is:

var num=0, nums = ['100','300','400','60','40'];

for(var i=0; i < nums.length; i++){            
        num += parseInt(nums[i]);  
}
  alert(num);
1

Javascript is treating your numbers as strings, and concatenating them together instead of adding them like you expect.

Use parseInt to convert them into integers before adding:

var nums = ['100','300','400','60', 40];
var num = 0;

for(var i=1; i < nums.length; i++){
       num += parseInt(nums[i], 10);
       alert(num);
}​

The second parameter tells parseInt to use base 10.

2
  • what about the keyword var in the for loop?
    – Besnik
    Commented Jul 27, 2012 at 11:39
  • I have eradicated all the var Commented Jul 27, 2012 at 11:39
1
var i, sum = 0, nums = ['100','300','400','60','40'];

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

alet(sum);

You shouldn't use the var statement inside a loop. Also the parseInt function used in other answers will always convert the number to an integer so it wouldn't work with floating point numbers. Prefixing the numbers with + will convert them to a number.

If you develop for the browser, using the reduce function might cause problems with older browsers - unless you find a polyfill for it.

1

Here's an example that uses an extension of the Number prototype, similar to LINQ's sum method:

Array.prototype.sum = function () {
  var result = 0;
  this.forEach(function (o) { result += Number(o); });
  return result;
};

var sum = ['100','300','400','60','40'].sum();
1

You can do something like this..

var nums = ['100','300','400','60','40'];

nums.reduceRight(function(a,b){return Number(a)+Number(b);})
1
var nums = ['100','300','400','60','40'];
let sum =0;
    for(let numbers of nums){
 sum+=parseInt(numbers);
     }
alert(sum);
2
  • Welcome to Stack Overflow! Code-only answers are not particularly helpful. Please add some descriptions of how this code solves the problem. Commented Jul 2, 2021 at 21:29
  • For arrays, it’s much easier to use a for…of loop to sum all the variables in the array . All you have to do is , declare a variable and set its value to 0. Then use the a for … of loop to iterate through the array and return the sum. Commented Jul 7, 2021 at 11:29
0

You can try this:

var arr = ['100','300','400','60','40'];
var total = 0; 
for(var i in arr){
  total += parseInt(arr[i]);
}

console.log(total);

Output will be: 900

Or if value is Float, then try this:

var arr = [100.00,300.50,400.75,60.00,40.00];
    var total = 0; 
    for(var i in arr){
      total += parseFloat(arr[i]);
    }
    
    console.log(total.toFixed(2));

Output will be: 901.25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.