Nested Loops

Loops that are inside of other loops are called nested loops.

The inner Loop runs completely (i.e. through all its iterations) for each single iteration or step of the outer loop. Examples:

for(var row = 1; row <= 4; row++) { // Outputs: var s = ""; // **** for(var col = 0; col < 5-row; col++) s += "*"; // *** console.log(s); // ** } // *

How many "steps" in total does this take? How many iterations of the outer loop? How many of the inner loop?

In the above case we can visually see how many as each star represents a step in the inner loop and all the stars represent the total of all steps taken. The number of rows represent the steps taken by the outer loop and the stars within each row the steps taken by the inner loop for that particular row.

// Creates a 2 dimensional matrix where each row/column position is equal // to the row times the column. var m = []; for(var row = 0; row <= 10; row++) { m[row] = []; for(var col = 0; col <= 10; col++) { m[row][col] = row*col; } } console.log(m);

//Print all the hex numbers from 00 to FF: var hex = "0123456789ABCDEF"; for(var a = 0; a < 16; a++) { for(var b = 0; b < 16; b++) { console.log(hex[a] + hex[b]); } }