Why the console returns this value

Why the console returns this value
0

#1

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


#2

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.


#3

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

   total += arr[i];

#4

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

-WWC


#5

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

#6

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.