# Nested Loops output

Hello everyone. good afternoon. Guys, I did not understand the output of this code. I understood the output of the first loop that will display the inside arrays of arr. However, when the nested array begins and uses the output of the first for loop I don’t get why the 0,1,0,1,0,1,0,1. I mean, I did not get the idea of how the nested loop works.

``````var arr = [[1,2], [3,4], [5,6], [7,8]];
var i;
var j;

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

for (j = 0; j < arr[i].length; j++) {
console.log(j)
}

}`````````

This is just logging the variable `j`, not anything from the array

If you want to get the values from the array try: `console.log(arr[i][j])`
Or more detailed: `console.log("i is " + i + ", j is " + j + " and arr[i][j] is " + arr[i][j])`

A stupid question: So, why the `arr[i].length;`?

If you want to get the values from the array try: `console.log(arr[i][j])`
Or more detailed: `console.log("i is " + i + ", j is " + j + " and arr[i][j] is " + arr[i][j])`

Because the inner loop is iterating over the subarrays

1 Like

I got the point: [0,1] would be the length of each array. as eight 0 and 1 would be the output of each array within the var arr. e.g.: the length of [2,3] are 0,1 and successively!? Four sub arrays with two values each will give the final output that I mention in the first question!? would be this the answer?

Try replacing your console.log with this and see how the variables change st each iteration

`console.log("i is " + i + ", j is " + j + " and arr[i][j] is " + arr[i][j])`

The length of each subarray is always 2, as there are two items in each one. `i` and `j` when used as `arr[i][j]` are the indexes of the elements inside the array

make sense. the output is:

``````i is 0, j is 1 and arr[i][j] is 2
i is 1, j is 0 and arr[i][j] is 3
i is 1, j is 1 and arr[i][j] is 4
i is 2, j is 0 and arr[i][j] is 5
i is 2, j is 1 and arr[i][j] is 6
i is 3, j is 0 and arr[i][j] is 7
i is 3, j is 1 and arr[i][j] is 8

then I can understand what each var does in the code. cheers.``````
1 Like