# Understating the Nesting For Loops

I am trying to break (the code given in example down) to understand but It is confusing me, below is my code and comments to see what I think it is in each loop. Then why result is different?

``````
fvar arr = [
[1,2], [3,4], [5,6]
];
for (var i=0; i < arr.length; i++) { // 0,1,2
for (var j=0; j < arr[i].length; j++) {
//arr[i] = [1,2]; j = 0
//arr[i] = [3,4]; j = 1
//arr[i] = [5,6]; j = 2
console.log("arr with ij is " +arr[i][j]);
//[1,2]
//[3,4]
//[5,6]
}
}
``````

More like this

``````for (var i=0; i < arr.length; i++) { // 0,1,2
for (var j=0; j < arr[i].length; j++) {
/** For i = 0  **/
//arr[i] = [1,2]; j = 0
//arr[i] = [1,2]; j = 1
console.log("arr with ij is " +arr[i][j]);
//[1,2]
//[1,2]

/** For i = 1  **/
//arr[i] = [3,4]; j = 0
//arr[i] = [3,4]; j = 1
console.log("arr with ij is " +arr[i][j]);
//[3,4]
//[3,4]

/** For i = 2  **/
//arr[i] = [5,6]; j = 0
//arr[i] = [5,6]; j = 1
console.log("arr with ij is " +arr[i][j]);
//[5,6]
//[5,6]
}
}
``````

Basically, Your arr[i] does not change until j has completed its loop entirely

1 Like

and I am lost. I don’t understand what is happening.

Do you understand how a single for loop works without nesting?

yes, I do. what is confusing to me when you wrote in comments

``````    /** For i = 0  **/
//arr[i] = [1,2]; j = 0
//arr[i] = [1,2]; j = 1
``````

why loop is going over arr[i] twice in each loop?

Because j has to finish before it goes to the next i iteration

Ok, if you forget about nesting for a second and ran just 1 single loop , this would your outcome

``````for (var i=0; i < arr.length; i++) { // 0,1,2
// arr = [1,2] // Inner loop would iterate through this first
// arr = [3,4] // Inner loop then iterates through this
// arr = [5,6] // Inner loop will finally iterates through this
}
``````

so when you include your inner loop it iterates through each content of the upper loop and
if you look at it separately, your inner loop will first

``````for (var j=0; i < arr.length; j++) {
// arr = 1
// arr = 2
}

``````

then after it finishes the above it goes to the next arr[i] which is arr

``````for (var j=0; i < arr.length; j++) {
// arr = 3
// arr = 4
}

``````

Finally it goes to the last arr[i], which is arr

``````for (var j=0; i < arr.length; j++) {
// arr = 5
// arr = 6
}

``````