Return sum of array values...HELP


#1

What is wrong/missing with my code?

//create a function called "loop" that accepts an array as a parameter and returns the sum of all the numbers in that array

//code here
var myArr = [1, 2, 3, 4, 5]
function loop(myArr) {
for (var i = 0; i < myArr.length; i++);
return i;
}

//Oops! Errors. Try again.
Function returned
6
instead of
21
when passed
[1,2,3,4,5,6]


#2

For loops aren't supposed to have a semi colon after the for statement when it's behind the first corresponding bracket. Which leads to our second problem, which is that you didn't put two corresponding brackets. Also, I don't think you're supposed to put myArr as a parameter of the loop function....


#3

Thanks. I fixed the first two problems, as for the third problem. The instructions say to create a function called 'loop' which accepts an array as a parameter. Is there another way to do that besides what I have? Thanks!


#4

Try:

var loop = function (myArr){}

Maybe it'll work now....?


#5

Nope :frowning:
var myArr = [1, 2, 3, 4, 5]
{
var loop = function (myArr){
for (var i = 0; i < myArr.length; i++)
return i;
}
}


#6

Hey...can I ask what level this is? I want to check out what it's about...


#7

It's on another coding site but I remember doing an array sum/function of some kind on Codecademy. Here is the link:
https://codecard.io/a/challenge/BEBaMBz3?sequence=Brp4wLU1

It's part of a coding challenge for a bootcamp I might go to. Thanks for your help.


#8

MAN! IT WAS SUCH A SIMPLE PROBLEM IN YOUR CODE!! Sorry... I was a few low a piece of loaves this time....:smiley: It was really just a simple mistake, and it's what I say a LOT of times. How could I have not seen that?!

First, no semi colons before the first corresponding bracket of your loop. Got that? Yeah, I see it :smiley: . Check. Each loop must have two corresponding brackets. See that? Nope. :smiley:

Look closely here:


#9

Let's fix the syntax, then discuss a greater issue...

var myArr = [1, 2, 3, 4, 5];
function loop(myArr) {
    for (var i = 0; i < myArr.length; i++) {
        return i;
    }
}

The greater issue is the return statement inside the loop. The loop iterates but once and that's it. We need some sort of function that works with i, and not return, but keep the loop going to full completion.

var myArr = [1, 2, 3, 4, 5];
function arrSum(myArr) {
    var sum = 0;     // declare and initialize an accumulator variable
    for (var i = 0; i < myArr.length; i++) {
        sum += myArr[i];
    }
    return sum;
}
console.log(arrSum(myArr));  // 15

#10

YES!!!!! Genius! Haha! I knew it had to be something super simple. Thank you!!!!! A guy at work and I at work had this idea too obviously unattentive to proper syntax. Thank you so much. :smile:


#11

@mtf, you actually saved me. :smiley:

I had no idea what was wrong... haha.