to illustrate where your code is wrong
function sum(arr) {
var i = 0;
for (var index = 0; index < arr.length; index++) {
return index += arr[i]; // this will return from your function in the first iteration
}
}
as the comment says, return will exit your function in the first iteration
also, you're adding to index, which is supposed to be the index into the array, you want to add to i, and then return i after the loop
so, the code should be
function sum(arr) {
var i = 0;
for (var index = 0; index < arr.length; index++) {
i += arr[index];
}
return i;
}
As another answer pointed out, a probably better alternative is to use array reduce function - however the code in that answer is not the "best" usage of reduce
function getSum(ary){
return ary.reduce(function(sum, value) {
return sum + value;
}, 0);
}
can actually be written
function getSum(ary){
return ary.reduce(function(sum, value) {
return sum + value;
});
}
This uses one less iteration, because there is no "initial value", and the first iteration adds index 0 and 1 together
Sure, it's not going to make a performance difference, but why not use built-in functions properly :p
returnexits the function, not the loop .. also, you're adding toindexrather thani, and usingias theindexwhich is stcuk at0