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 i
is 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.