0

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
asked Aug 11, 2014 at 21:37
1
  • 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. Commented Aug 11, 2014 at 21:41

1 Answer 1

3

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.