Why the console returns this value

hello,

I ran this simple code in the console log and i received a value that I don’t understand how the machine came to it:

why it returns 6 instead of 10?

var arr = [1,2,3,4];
            var total = 0;
            for(i=0; i<arr.length; i++){
               total += i;
            }
            console.log(total);

i will have values 0, 1, 2, 3, which add up to 6. The length of the array is 4, but i will not be assigned this value because the condition in the for loop is i<arr.length, not i<=arr.length.

You are summing your increment variable (i) and not your data (arr). If you want your data summed, you need:

   total += arr[i];
3 Likes

Yup you are summing your counter. Follow @ksjazzguitar sage advice.

-WWC

1 Like

The values we are incrementing are from i. However, we want to increment the values from our array or arr[i]

var arr = [1,2,3,4];
var total = 0;
  for(i=0; i<arr.length; i++){
     total += arr[i]; // <---- this should be an index in your arr called by the incrementer
  }
console.log(total);
1 Like

To understand how the console arrived to this value, we need to re-trace the values taken by the variable i (which are added to the variable total).

First off, let’s start with boundary value: arr.length = 4 since the array consists of 4 elements (1,2,3 and 4).

Next, we are looping and stopping at i < arr.length, i.e., i < 4. Following that reasoning, i will take the successive values: 1, 2 and 3. Adding those together gives: 1+2+3=6.

Since total does just that (i.e., adds the incremental values of i), then total will have a final value of 6.

1 Like