Basic JavaScript - Iterate Through an Array with a For Loop

Tell us what’s happening:

Describe your issue in detail here.
Hi, so the the issue I’m having is actually not the exercise but the example.
This is the example below:

const arr = [10, 9, 8, 7, 6];

for (let i = 0; i < arr.length; i++) {

My understanding is that arrays have zero based indexing so for the example above, the total length of the array should come out as 4.

Next, the optional expressions in the for loop are :

for (let i = 0; i < arr.length; i++) {

which to me is equivalent to this below because like i mentioned earlier, the length of the array is 4 as opposed to 5:

for (let i = 0; i < 4 ; i++) {

if this is the case, then the code should terminate when it reaches the 4th number because “i” should be less than the length of the array.
Basically the answer in my mind should be 10,9,8,7 but instead it outputs 10,9,8,7,6 which is what is confusing me.

Learning Javascript for the first time so please explain to me where my reasoning is wrong. Thanks!

Your code so far

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

// Only change code below this line

Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/ Safari/537.36

Challenge Information:

Basic JavaScript - Iterate Through an Array with a For Loop

1 Like

Ya, zero-based indexing can be a little confusing at first. The length of an array will always be the number of items in the array. So in the example, there are five numbers in the array and thus the length of the array is 5. So you start counting at 1.

But when you are accessing an individual item in an array then you start at 0. So directly accessing the first item in the array is array[0].

1 Like

oh I see. Thank you! that cleared up all my confusion


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