Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript Array Iteration with a For Loop

Nicholas Wallen
Nicholas Wallen
12,278 Points

How does it differentiate between the two different i counters?

for (let i=0; i< myRandomList.length; i++) { console.log('Item ' + i + ' in the array is ' + myRandomList[i] ); }

By using myRandomList[i], does that tell the compiler to look at the actual item in that place, versus just the index value?

If you access an array value in a loop then it is going to access the index multiple times.

So i = 0 .... // display arr[0]

i = 1 ... // display arr[1]

etc.

So it doesn't differentiate between them. They are the same value but the value will change with each loop and this is how you can loop through and display an array's contents (for example).

1 Answer

The 'i' variable is of type integer. To go directly to your question, it is not differentiating between the two different i counters because they are not different. You only have one i counter, which is the variable declared in the for loop.

The first i in you console.log statement is directly referencing the value of i, which in the first pass through the loop is 0. When referencing i the second time in your console.log statement you are using the value of i to find the value in the array for that index.

Using i by itself will give you the value of i. Using it in the place of the array index value will return the value at that index in the array.

Hope this helps!

yea that cleared it up for me, thanks a lot!