Understanding nested for loops in javascript

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

This is an array of arrays. It is a little bit easier to read like this:

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

That makes it a little bit easier to see that you have an array of 3 arrays. The outer ‘for’ will loop through each of 1st level arrays. So the very first outer for loop when i=0 you are going to grab the first inner array [1,2]:

for (var i=0; i < arr.length; i++) {
    //First time through i=0 so arr[i]=[1,2];
}

In the inner loop you are going to loop through each of the 3 inner arrays one at a time.

for (var j=0; j < arr[i].length; j++) {
    //Handle inner array.
}

This argument grabs the length of the inner array:

arr[i].length

So on your first time through the outer loop i=0 and arr[i] is going to equal [1,2] because you are grabbing the 0th element. Remember, arrays elements are always counted starting at 0, not 1.

Finally you are printing out the results with:

console.log(arr[i][j]);

The first time through you can break it down a little. i=0 and j=0. arr[0][0] which translates as grab the first element from the outer array and then the first element from the first inner array. In this case it is ‘1’:

[
    [1,2], <-- 0
    [3,4], <-- 1
    [5,6]  <-- 2
];

The code will loop through the first first set [1,2], then the second [3,4], and so on.

Leave a Comment