Waqar
Waqar

Reputation: 185

Scope of variable inside for loop

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;
}

Upvotes: 0

Views: 47

Answers (1)

Pointy
Pointy

Reputation: 413702

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.

Upvotes: 3

Related Questions