Marc Andre Jiacarrini Marc Andre Jiacarrini - 1 year ago 121
Javascript Question

The sum of all the elements in an Array

i am trying to do some examples.
i want to sum all the elements of the array
here is my code

var marks = [10, 20, 30, 40];
var total = 0;

for (var singleMark in marks) {
total += marks;

console.log("the total marks re " + total);

But the results displayed is
the total marks re 010,20,30,4010,20,30,4010,20,30,4010,20,30,40

Please help me and tell me where am i doing it wrong.Thanks.
I can take the for loop but i want to learn using foreach as in Javascript the definite guide book it says so

Answer Source

For in will go over properties of objects. If you where to use for in on an array it will return you the index it is iterating over.

You should be using forEach to iterate over arrays.

marks.forEach(function(element, index){

The element value is the element from the array, while the index value is the index that forEach is currently at. index is optional and does not need to be included.

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