 # Can someone help me understand the logic of nesting for loops

Before I begin this exercise I really want to know the logic and how things work in the example:

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

What do you not understand specifically?

The outer loop (using variable i) references each sub array and the inner loop iterates through each sub array’s elements.

Assuming you’re clear on how a for loop that is not nested works

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

Let’s just loop through that with a plain un-nested for loop

``````i = 0   arr = [1,2]
i = 1   arr = [3,4]
i = 2   arr = [5,6]
``````

OK, with nesting

``````arr is an array. Lets loop through that.

i = 0   arr = [1,2]  outer

Hey! arr is an array too. Lets loop through that too while we're here - inner
j = 0   arr = 1
j = 1   arr = 2

i = 1   arr = [3,4]  outer

Hey! arr is an array too. Lets loop through that too - inner
j = 0   arr = 3
j = 1   arr = 4

i = 2   arr = [5,6]  outer

Hey! arr is an array too. Lets loop through that too - inner
j = 0   arr = 5
j = 1   arr = 6
``````
3 Likes