For Loop not clear for condition i < myArr.length

Tell us what’s happening:
Describe your issue in detail here.
I am confused and don´t know why the sum is 20. I thought the code added LESS than the array length…In this array I expected only const myArr = [2, 3, 4, 5, 6]; I expected only the sum to be 2+3+4+5=14 not adding everything because in the for lood there is this condition i < myArr.length

  **Your code so far**

// Setup
const myArr = [2, 3, 4, 5, 6];

// Only change code below this line
var total = 0; 
for(var i = 0;i < myArr.length; i++){
total += myArr[i];
  **Your browser information:**

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.110 Safari/537.36

Challenge: Iterate Through an Array with a For Loop

Link to the challenge:

Remember that arrays are zero indexed. That means that the index of the last element is 1 less than the length.

1 Like

Try this:

for(var i = 0;i < myArr.length; i++){
  console.log(i, myArr[i]);
  total += myArr[i];

Thanks for quick reply…Therefore for this array: [2, 3, 4, 5, 6] the length is 5 though with the indexing number 6 is at “position” or index 4, hence 2,3,4,5 AND 6 are added, right?

If I’m understanding you, yes. It’s one of the “odd” things about zero-indexing. If you have a 5 element array, the index of the last element is 4. You get used to it, but sometimes you still make mistakes. They fall into the category of OBO errors (off by one).

To anticipate your next question - Why zero index?

It is historical. In the olden days (gather around kids while grandpa tells a story) you dealt a lot with memory addresses. For an array, you stored the memory address of the first element and then added however many you needed to get to the next. If your element was 4 bytes, then the 17th element would be at base address + (17 - 1) * 4. That 17 is one indexed. If we think of things as zero indexed, we get a general formula of base + index * size - easier to deal with mentally. Another way to think about it is that the 1st element has an offset of zero.

It seems like a weird way to think, but you get used to it.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.