Nested Loops
A loop inside a loop
A nested loop is a loop written inside the body of another loop. The one on the outside is the outer loop and the one inside it is the inner loop.Every time the outer loop takes a single pass, the inner loop runs all the way from its start to its finish. Then, on the next outer pass, the inner loop starts over from scratch.
Multiply, do not add
The outer loop takes 2 passes and the inner loop takes 3 passes inside each one of them, so the inner body runs 2 times 3, which is 6 times in all.Two loops written one after the other add up. Two loops nested inside each other multiply.
Building a row as a string
A console.log always ends the line. There is no way to print half a line and come back to it later, so several values only land on ONE line if they are joined into a single string first.The idiom is: start with an empty string just outside the inner loop, glue one more piece onto it with + on every inner pass, and print the finished string once, after the inner loop is over.
An inner bound that can change
The inner loop does not have to run the same number of times on every outer pass. If its bound mentions the outer variable, the amount of work inside one outer pass changes as that variable climbs.The program below prints a multiplication table, building one row per outer pass, and counts the numbers it prints. Run it, then make each change below and run it again. Press Reset before each change.
• In
let rows = 3;, change 3 to 4.• Change
j <= cols to j <= i.• Cut the line
console.log(line); and paste it just below printed = printed + 1;.let rows = 3;
let cols = 5;
let printed = 0;
for (let i = 1; i <= rows; i++) {
let line = "";
for (let j = 1; j <= cols; j++) {
line = line + (i * j) + " ";
printed = printed + 1;
}
console.log(line);
}
console.log("Numbers printed: " + printed);
Output
Press Run to see what this program prints.
Note: This IDE is for experimenting with the code in this lesson. Your changes are not saved, and refreshing the page puts back the original lesson code.