Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding nested for loops in javascript

I'm learning JavaScript at the moment on freecodecamp and they have an example for nested for loops in one of their excercises:

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

With console.log = 1 2 3 4 5 6 undefined.

I understand for loops more or less, and I understand that [i] and [j] are used to access the array (I think?). I just don't understand why at the end it just prints out those numbers? I found this question asked a few years back but it just explains how to write them, not how they work:

For loop in multidimensional javascript array

I broke it down into:

var arr = [  [1,2], [3,4], [5,6]];for (var i=0; i < arr.length; i++) {
 console.log(arr[i]);}

Which prints out

[ 1, 2 ]
[ 3, 4 ]
[ 5, 6 ]
undefined

and

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

which prints out:

[ 1, 2 ]
[ 1, 2 ]
[ 3, 4 ]
[ 3, 4 ]
[ 5, 6 ]
[ 5, 6 ]
undefined

and

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

which prints out

[ 1, 2 ]
[ 3, 4 ]
[ 1, 2 ]
[ 3, 4 ]
[ 1, 2 ]
[ 3, 4 ]
undefined

I understand the first two arr[i]. The loop iterates through the array and prints out the individual elements (in this case an array) and in the second one I guess it just does it twice because there are two loops. What I don't understand is:

  1. why the last array in arr[j] is not printed out (where did the [5, 6] go?)
  2. why arr[i][j] suddenly eliminates the arrays and just prints out the numbers
  3. where the 'undefined' comes from

Could anyone help me out with this and explain the steps the code takes before printing it out in the console? I would really like to understand it but don't even know how to search for this question the right way.

like image 475
stellatores Avatar asked Apr 04 '16 21:04

stellatores


People also ask

How does nested for loops work in JavaScript?

The nested loop is also called as inner loop and the loop in which the nested loop defined is an outer loop. The outer loop always executes first and the inner loop executes, the inner loop executes each time the outer loop executes once.

How do you explain nested loops?

A nested loop is a loop within a loop, an inner loop within the body of an outer one. How this works is that the first pass of the outer loop triggers the inner loop, which executes to completion. Then the second pass of the outer loop triggers the inner loop again. This repeats until the outer loop finishes.

What is a nested for loop explain with an example?

If a loop exists inside the body of another loop, it's called a nested loop. Here's an example of the nested for loop. // outer loop for (int i = 1; i <= 5; ++i) { // codes // inner loop for(int j = 1; j <=2; ++j) { // codes } .. } Here, we are using a for loop inside another for loop.


3 Answers

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.

like image 144
Gremash Avatar answered Oct 09 '22 23:10

Gremash


The double for loop you have above works like so:

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

 for (var i=0; i < arr.length; i++) {
  // i = 0, then we loop below:
  for (var j=0; j < arr[i].length; j++) {
    //here we loop through the array which is in the main array
    //in the first case, i = 0, j = 1, then we loop again, i = 0, j = 1
    console.log(arr[i][j]);
    //after we finish the stuff in the 'j' loop we go back to the 'i' loop 
    //and here i = 1, then we go down again, i, remains at 1, and j = 0, then j = 1
    //....rinse and repeat, 
  }
}

In plain english:

We grab the first element in the main array, which is an array itself, we loop through that, and log at each index, this is terminated by our length condition in the second loop. We then move to to the next index of the main array, which is an array itself.... and so on, until we reach the end of the main array

To access and index in the main array, we need to use array[i] - that index holds an array - so to go INTO that array, we need to use array[i][j]

Hope that makes sense!

like image 34
omarjmh Avatar answered Oct 09 '22 21:10

omarjmh


Despite some caveats of using for-in loops on arrays, they can imo sometimes help to clear the mess in nested loops a bit:

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

for (i in arr){
      for (j in arr[i]){
        console.log(arr[i][j]);
      }
    }

Also code visualization can clarify execution!

like image 39
upgrd Avatar answered Oct 09 '22 22:10

upgrd