CodeNewbie Community

Discussion on: How do you create nested loops?

djuber profile image
Daniel Uber

Hi Collin,

I think you want to just put the "inner" loop inside the "outer" loop. For example

var i, j; 

for(i=0; i<3; i++) {
  for(j=0; j<3; j++) {
    console.log(i, j, i+j);
0 0 0
0 1 1
0 2 2
1 0 1
1 1 2
1 2 3
2 0 2
2 1 3
2 2 4
Enter fullscreen mode Exit fullscreen mode

In this case, the outer loop runs first, setting the variable i to it's value, and while keeping that value constant, the inner loop runs setting j from 0 to 2 in order. When that's done, the outer loop sets i to its next value, and the inner loop runs again.

You can see from the logged statements the sequence these variables step through.

Why would you do this? It's not uncommon if you have a nested structure (like an array of arrays, or an array of objects) to want to do the same "loop" to each item in the top level collection.

This wouldn't have to be for loops - you could use forEach or while or any other "loop" construct, the key idea is that a variable set during the outer loop's execution is "fixed" while the inner loop is running, and the inner loop will run once for each value in the outer loop. In every case, put the inner loop inside the body of the outer loop - any place you would have put another expression you can add a loop.

wannabecoder profile image
Collin Author

Thanks very much, this helps a lot!