Nested For Loops

On a not-so-stormy, not-so-gloomy night… about a month ago, a fellow peer asked a question about “nested for loops” (in JavaScript) in my coding boot camps Slack channel. The person was had just started to try and learn JavaScript, and decided to try and tackle some of the challenges on Eloquent JavaScript. I tried to think about the best way to explain on how it worked, in the simple English and analogies.

For explanations sake, a for loop, defined by Mozilla Developer Network…

The for statement creates a loop that consists of three optional expressions, enclosed in parentheses and separated by semicolons, followed by a statement (usually a block statement) to be executed in the loop.
for ([initialization]; [condition]; [final-expression])
statement

Initialization — This is where you would typically declare your variable, often a counter. The variable declared or initialized is in the same scope that the for loop is in, meaning you can use it in the within statement’s scope.

Condition — Simply, this creates a rule for the loop on when to continue or stop looping. You can put your operators here to do a comparison, or evaluation on where to continue or not.

Final Expression — This is what the programmer defines on what to do if the condition is true. Usually, this is incremental or decremental of the initialized variable (or counter).

Statement — Inside the statement block, a programmer will define what you want to have done as the loop occurs.

Essentially…

A nested for loop, is a for loop inside of it.

The first analogy was asking the peer to think of at like it a old, on the wall, two handed clock. In a clock, there are two things that are counting; there are minutes that sum up to hours, and there are seconds that sum up to minutes.

The loop that calculated minutes would be on the outer, and the loop for the seconds would be nested in the minutes loop. Just like on a clock, or time keeping, minutes are dependent on when the seconds loop makes one revolution.

The peer wanted me to code this out, but it came out to be a really inefficient program due to the amount of loops that had to occur.

for (var minutes = 1; minutes <= 60; minutes++) {
console.log("Minute: " + minutes + "\n");
for (var seconds = 1; seconds <= 60; seconds++) {
console.log("Seconds: " + seconds);
}
}

Seeing this, she got the basic concept even without running it. So for the sake of just writing a few lines of code to illustrate the analogy, she could understand that the context, if multiple dimensions or if multiple counts are required, this is how you would use a nested for loop.

One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.