Hi, I’m struggling to grasp for loops. I just completed the nested for loop and I understand it in theory, but there are still aspects that I don’t understand.
I noticed that sometimes when dealing with an array [ i ] will be used. What exactly is this meant to represent? Especially since i is often used inside the round brackets when writing a for loop. This is the example that was used in the nested for loop section:
var arr = [
[1,2], [3,4], [5,6]
];
for (var i=0; i < arr.length; i++) {
for (var j=0; j < arr[i].length; j++) {
console.log(arr[i][j]);
}
}
This is the example used in the iterate through a for loop section:
var arr = [10, 9, 8, 7, 6];
for (var i = 0; i < arr.length; i++) {
console.log(arr[i]);
}
What am I asking the computer to do when I include arr[i]? Thanks!
It is like a placeholder that represents each number in the array. As the loop starts, if the loop is at 0, i is 0, if the loop gets to 3 then i becomes 4. Something like that.
Historically (gather `round kids while grandpa takes out his pipe and tells a story)…
That array variable holds an address. Say you have an array of integers, they are 4 bytes each. If the first memory location is 5000, then that is where the first integer will be, the second at 5004, the next at 5008, etc. So…
So, the index tells us how far into that memory to dig. This is also why we start counting with zero, so the first element will have an offset of zero.
Of course, this doesn’t quite ring true in JS - we don’t have an integer type and an array can be of any type even within an array - but this is the basic idea. We can’t even do this kind of low level memory access in JS (like you can in C or definitely Assembly), but it’s kind of what is happening under the covers.