Below is what the code looks like broken out, with some explanation. Following that, you will see a cleaner version of a for loop.
It took me some time to realize that this block of code does exactly as it reads. let “i = 0” and while “i is less than 10”, run the block of code and increment “i” by 1. I wish I knew why this took me the better part of a program to comprehend, but it could have been due to the other variations of loops that can be used.
Now imagine what went through my head when I saw a for loop, followed by a second for loop. I was already lost on the first loop. It wasn’t till I started doing codewars (wish I had started every morning with a code war), that I was forced into a solution that required a nested for loop.
How I got comfortable with what a nested loop does was by understanding how a single loop worked. By creating the for loop above, and logging “i” in the console, I saw it logged numbers from 0–9.
This showed me that while “i” is at 0; 0 is logged, then “i” is increased by 1, and the console log code block is run again. Seems simple on its own, once you get a simple bit of code in the loop. Now, what happens when you add a second loop inside of the for loop?
From what I have read, the convention is to set the variable “j’ or “k”; below you will see my nested for loop function:
This looked very confusing to me until I logged both of my variables in the console. What I learned was that the first for loop will run with “i” at 0 and this will then run the second loop. It is in the first for loops block of code to run before the “i” variable is incremented. When I console logged “i” and “j” in the second loop, “j” is going to run through its code from 0–9, while the “i” variable is 0. It is not until the second loop is done that the first loop will increment and run the second loop in its entirety again. This will repeat itself until “i” is no longer less than 10.
Understanding how a nested for loop works was an exciting moment during my time programming. This has been a fun topic to learn and tinker with while I try to devise new ways to solve problems that may require nested loops.