Could someone tell me if I understand this properly?

Could someone tell me if I understand this properly?
0.0 0

#1

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]);
}
}

firstly i === 0 so we check the length of arr which is 3 and i becomes one. i is now the first part of the arr ([1,2]). Then j runs against i and comes back with 1 as i === 1 so now j === i === 1 so the console returns arr[i][j] which === arr[1][1] which is arr[1][2].

am I way off the mark here? I seem to be having a real struggle with for loops. If its wrong can someone break the code down for me and explain it please. Thanks a lot.


#2

You’re not too far off, but you’re numbers are wrong.

for(var i = 0; i < arr.length; i++)

Your first couple of points are correct. i is declared and initialized to be 0. Then it’s checked against the length of the array arr, which is 3. However, i doesn’t increment here. If i is less than the length of arr, it executes the code in the for loop, which is another for loop in this case.

for(var j = 0; i < arr[i].length; j++)

j is declared and initilized to be 0. The it’s checked against the length of the array that occupies the first index of arr, which is 2. If j is less than that length, it executes the code inside the for loop, this time a call to console.log(). At this point, i and j both have the value of 0. Once the console.log() function is done, we return to the second for loop and complete the next instruction, j++. j is again checked against the length of arr[0] - j is 1 and the length of arr[i] is 2, so the inequality is true and we execute the code in the second for loop again. This process is repeated until all of the for loops are complete.

Does that help at all?


#5

Well, I took a bunch of shortcuts. Your answer is way clearer than mine.


#7

Such a great feeling when something just clicks in your mind. Had to stare at it for a good ten minutes but I get it now. Thanks both.