ughdeeb
ughdeeb

Reputation: 21

How does iterating over an array using a for loop REALLY work?

I am a javascript beginner and I understand how to iterate over an array and how to use it, but I am trying really, really hard to understand WHY it works.

For example:

let myArray = ["one", "two", "three", "four"];

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

console.log(myArray[i]);
}

I understand what is going on in each of the 3 parts within the for loop, but I don't really understand how the iis accessing/communicating with/connected to/exchanging data with the array myArray. At which point in this code are we telling javascript that "i" is somehow connected to "myArray"?

At first I thought something was implied or implicit in the for loop itself, i.e., that when we write i < myArray.length it is somehow implying that i = myArray (that "i" is assigned to the value of whatever is in myArray). But upon further thought, i < myArray.length is simply the length of the array (in this case, 4), and doesn't really connect the two.

So this has opened up a whole conceptual can of worms for me about what the "i" really is here besides just a variable in a for loop. I have been thinking about the "i" as a sort of ghost/temporary variable that we create that will do the looping for us and then disappear once it is done (I am not even sure if that is the correct metaphor here).

I apologize in advance if I am not articulating this clearly, as I am just a beginner.

Thanks in advance.

Upvotes: 1

Views: 122

Answers (1)

Someone
Someone

Reputation: 45

The variable i is simply just a variable. It is a number that is incremented with each iteration, and stops incrementing when it increments through all the indexes in the array. The variable i is not in connected with myArray except that it loops through all the indexes of myArray (0, 1, 2, 3). It starts with 0, and increments itself while doing the commands inside the for loop (getting a certain element in myArray using bracket notation).

E.g, the variable i starts at a value of zero. While being 0, myArray is called in the for loop, but specifically for the 0th index, which is "one". Then the variable i increments, and the code in the for loop calls the 1st index of the array, and so on until the conditional i < myArray.length is met, which marks the upper boundary of the indexes of the array.

I hope this helps!

Upvotes: 2

Related Questions