This function returns the total from an array, and it works perfectly. But if i initialize total inside the for loop, it does not return the sum. Can you please tell me why?
function sum(arr) {
var total=0;
for (var i=0;i<arr.length;i++){
total += arr[i];
}
return total;
}
4444
3,73010 gold badges35 silver badges47 bronze badges
-
When you initialize a variable inside the loop, you are creating a new variable with the assigned value every time. Hence the previous value is lost.rdp– rdp2014年08月11日 21:41:35 +00:00Commented Aug 11, 2014 at 21:41
1 Answer 1
If you initialize it inside the loop, then the initialization happens on each iteration. I would use the word "reinitialize" in fact. I mean, it's just basic control flow — you initialize an accumulator variable before the loop begins, and then you modify it on each iteration of the loop.
answered Aug 11, 2014 at 21:38
Pointy
415k62 gold badges600 silver badges633 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
lang-js