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.
return
statement after the loop, not inside it. Also, you should use the parameter namearr
inside the function.return answer;
immediately terminates the loop. Move it outside of the loop.var i
declaration and the standardfor
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.