2

I am adding up the values in array by iterating through the array with a for-loop but it is only returning the first value. I am alerted 2 instead of 2014 like expected.

What am I doing wrong?

enter link description here

JavaScript

$(document).ready(function() {
    var array = [2, 2, 10, 0, 50, 1900, 25, 25];
    function arraySum(arr) {
        var answer = 0;
        for (i = 0; i < array.length; i++) {
            answer += array[i];
            return answer;
        }
    }
    var response = arraySum(array);
    alert(response);
});
3
  • 2
    Put your return statement after the loop, not inside it. Also, you should use the parameter name arr inside the function. Oct 30, 2015 at 17:56
  • 1
    return answer; immediately terminates the loop. Move it outside of the loop. Oct 30, 2015 at 17:56
  • My answer utilizes a jquery foreach loop and eliminates the lack of a var i declaration and the standard for loop structure that trips up so many people for silly reasons. You've loaded the library, you might as well use it where you can. It also defects the type of object (whether object array or array) being iterated through.
    – CSS
    Oct 30, 2015 at 18:06

6 Answers 6

5

Because you put the return statement inside of your loop, it is exiting the function with the value of answer when it first hits this return statement (which is 2). What you actually want is this:

$(document).ready(function() {
    var array = [2, 2, 10, 0, 50, 1900, 25, 25];
    function arraySum(arr) {
        var answer = 0;
        for (var i = 0; i < array.length; i++) {
            answer += array[i];
            // DON'T return here
        }
        // Return HERE
        return answer;
    }
    var response = arraySum(array);
    alert(response);
});

If this doesn't make sense, think of it this way:

You want to perform an action eight times, and when it's done you want to do something with the result. In this case you're adding numbers eight times and then alerting the total. Unfortunately, if you say return in the loop, it's going to try to "do something" (return) after each and every one of those actions (the additions). Because it's trying to return after each of these actions, the loop actually breaks after the first action, and never gets to add the last seven numbers. If you wanted to watch this process play out, you could actually put the alert where your return statement used to be, and watch it get hit after every iteration (thus receiving eight alerts).

As a side note, you should also define "i" with var i, as you can really screw with scope by forgetting the "var". I have fixed this mistake in the code above as well. Thank you Ryan for drawing attention to this.

3
  • 1
    Since you're at it, you should also define i... Oct 30, 2015 at 17:58
  • Not unrelated since it can break the loop structure to use an undefined variable. JS is very forgiving, but there are situations in which this would be the error preventing good print out.
    – CSS
    Oct 30, 2015 at 18:05
  • While you are absolutely correct that this could absolutely cause erratic behavior, I feel like this is "unrelated" in so much as that it is not the cause of the asker's problem in this particular case. That said, I have revised my answer. Oct 30, 2015 at 18:08
0
$(document).ready(function() {
var array = [2, 2, 10, 0, 50, 1900, 25, 25];
function arraySum(arr) {
    var answer = 0;
    for (i = 0; i < array.length; i++) {
        answer += array[i];           
    }
    return answer;
}
var response = arraySum(array);
alert(response);
});
0

You are returning the value inside of the loop. When the loop executes the first time, it adds the first array value to answer, then returns answer. At this point, your function is finished running.

If you move the return answer; below the loop, this will work as expected.

$(document).ready(function() {
    var array = [2, 2, 10, 0, 50, 1900, 25, 25];
    function arraySum(arr) {
        var answer = 0;
        for (i = 0; i < array.length; i++) {
            answer += array[i];            
        }
        return answer;
    }
    var response = arraySum(array);
    alert(response);
});
0

Not sure if this is some kind of test :)

You have a return statement within your FOR loop. So the loop return the result after calculating (0 + array[0])

$(document).ready(function() {
    var array = [2, 2, 10, 0, 50, 1900, 25, 25];
    function arraySum(arr) {
        var answer = 0;
        for (i = 0; i < array.length; i++) {
            answer += array[i];
            //return answer; remove this line
        }
    }
    var response = arraySum(array);
    alert(response);
});

0

You can just use this:

$.each(array, function(index, value) {
    answer += value;
});
return answer;

since jquery has a built-in foreach function.

0

In addition to what everyone has already said, while the function still operates as it should when you move return outside of the loop, I would change how you are calling the array in the function and loop.

Your array is titled "array". You are calling it in the function parameters as "arr", thus I think in the subsequent for loop that's in the function you should label the array call as "arr" too. Doing it either way gives me the right answer of 2014, but I think keeping the function array variable titled the same throughout its execution is the best choice.

$(document).ready(function() {
var array = [2, 2, 10, 0, 50, 1900, 25, 25];
function arraySum(arr) {
    var answer = 0;
    for (i = 0; i < arr.length; i++) {
        answer += arr[i];
    }
    return answer;
}
var response = arraySum(array);
console.log(response);
});

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