0

I am trying to create a function that sum all numbers in an array! I am new to JavaScript and in need of someone pointing me in the right direction!

function sum(arr) {

    var i = 0;

    for (var index = 0; index < arr.length; index++) {
        return index += arr[i];
    }
}

sum([1, 2, 3]); //6
1
  • 2
    return exits the function, not the loop .. also, you're adding to index rather than i, and using i as the index which is stcuk at 0 Commented Aug 3, 2017 at 23:47

5 Answers 5

1

Lots of basic issues with the code.

You need a separate variable to accumulate the result in. Your code is writing into the index variable of a for loop. This is wrong for a number of reasons.

You also return after the first iteration of the loop.

Assuming you want to use a for loop (which is not the least amount of code),

function sum(arr) {    
  var sum = 0;
  for (var index = 0; index < arr.length; index++) {
    sum += arr[index];
  }    
  return sum;
}
Sign up to request clarification or add additional context in comments.

Comments

1

Use Array.reduce() for that:

function getSum(ary){
  return ary.reduce(function(sum, value) {
    return sum + value;
  }, 0);
}

console.log(getSum([0, 1, 2, 3]));

3 Comments

Thanks!! I have to write as a function that uses one parameter (arr - an array of integers)
@MarioGomez then just put the code in a function. This is the correct answer
"this is the correct answer" ... yes, except it does not show where the original code went wrong, there's no value to simply giving an answer that uses reduce without at least some explanation of why the code in the question is failing - besides, this is actually NOT the best use of reduce anyway ...
1

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

3 Comments

Thanks @jaromanda x !! I am begginer in Javascript! Your explanation makes a lot sense !
"but why not use built-in functions properly" It is not improper to use the function as I have. It came directly from MDN, by the way.
sorry, "improperly" was too harsh @ScottMarcus - also, a later example [0, 1, 2, 3, 4].reduce( (prev, curr) => prev + curr ); shows how without an initial value :p
1
function Sum(arr) {

   var sum = 0;

   for (var index = 0; index < arr.length; index++) {
       sum += arr[index];
   }
   return index;

}

Sum([1, 2, 3]); //6

Return immediately exits a function. Your code will never sum values. What is 'i' in your code!?! And what index do!?

7 Comments

Anyway, Use upper case for first character of function name no - the "convention" is to use upper case for a "class" name ... i.e a function that is supposed to be called with the new keyword - and it's only a convention
Maybe you are right, i'm C programmer, so function means something else in my pov.
does C have a case convention for functions? I know it's not a "rule", considering the entry point for C programs is main not Main :p
int Sum(List<int> numbers){...}
Something like this.
|
0

Here's how you get your function to work:

  function sum(arr) {
     // this is the variable we're going to add our numbers onto
     var acc = 0;

     for (var index = 0; index < arr.length; index++) {
        // don't return here, return is used to return from a function
        acc += arr[index];
     }
     // after adding all numbers, return the sum
     return acc
   }

   sum([1, 2, 3]); //6

But there are built in ways to do this, like Array.reduce() like Scott Marcus mentioned.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.