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.
i < myArray.lengthandmyArray[i].iis just a regular variable that starts at0and gets incremented byforon each iteration, as long as it's less than the length of the array. In your example it's being used to access the different indices of the array inmyArray[i]. For example,myArray[0]andmyArray[1]... etc. It's like if I had four numbered (indexed) bins and you wanted to see what was in each, you could come to me and say show me what's in the third bin, and that's the same asmyArray[2](since array indices begin at zero)iandmyArrayiandmyArray, you are just asking themyArrayto give you the value at the index of the number iniat the time you domyArray[i](e.g.myArray[0],myArray[1],myArray[2], etc.). Arrays work like that because that is how they are defined to work. Array on MDN