Iterating Through an Array with a For Loop; why arr[i]?

Tell us what’s happening:
Describe your issue in detail here.

In the example code, I’m not understanding why we write arr[i] in the console.log.
How is [i] related to the array?

I understand that we initialize the loop with i = 0, the condition being i < arr.length, which to me means that the loop will continue to go until i < arr.length is no longer true, and the final expression i++ will make sure that the loop will not continue past i = 4 as the length of the array is (all elements - 1) due to arrays indexing at the start at 0.

I just can 't wrap my head around why we’re using bracket notation on the [i] in console.log(arr[i]);

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

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

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 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.99 Safari/537.36

Challenge: Iterate Through an Array with a For Loop

Link to the challenge:

You access properties in an array the same as any other object in JS: someObject[key] or someObject.namedKey.

So the alternative would be array.i and as the array doesn’t have a key i then it would just log undefined over and over.

Whatever is in the brackets gets evaluated first, so the i in array[i] is 0 first, then 1, then 2 and so on


I would say that sometimes it’s better to be verbose at first.
If you think what the “i” variable stands for, it will be much clearer.
It usually stands for index, and much as you can use any arbitral value you can use it on the array because - if you get the index of the array, you get out the element of the array that is stored at that index.
Take a look at the example here → Indexed collections - JavaScript | MDN it should clear up your doubts.

1 Like

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