The [i] in arrays and loops, what's it for?

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!

array[index] is a way to access element at index from the array

var array = ['a', 'b', 'c'];
array[2];
// → 'c'

When using for loop for example like this:

var array = ['a', 'b', 'c'];
for (var index = 0; index < array.length; index++) {
  console.log(array[index]);
}
// → 'a'
// → 'b' 
// → 'c'  

index === 0 it will print a
index === 1 it will print b
index === 2 it will print c


In case we have nested arrays, like in your example:

var array = [ [1,2], [3,4], [5,6] ];

You can access nested arrays using another pair of square brackets.

console.log(array[1]);
// → [3, 4]

console.log(array[1][1]);
// → 4
1 Like

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…

const MEM_LOCATION_ARRAY = 5000;
const SIZE_OF_ELEMENT = 4;

function getElement(index) {
  return MEM_LOCATION_ARRAY + (SIZE_OF_ELEMENT * index);
}

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.

3 Likes

Thank you, this is a very good explanation!