It is possible to nest loops inside each other.
This means that each time the outer loop performs a single iteration, the inner loop iterates from start to finish.
Run the code in the editor to get a feel for how nested loops behave.
Variable Names
Notice how the outer loop uses an i
variable while the inner loop uses a j
variable.
Since we used let
to define these variables, they are scoped to the block where we declared them. That means they could both be i
if we wanted them to be, as the inner i
would be a different variable than the outer i
.
Using different variable names makes the code easier to read, as we don't have to ask ourselves "which i
is this?"
For nested loops, it is common to name the variables i
, j
, k
, etc. to make it easy to see which loop is using the variable.
Many Options
It is possible to nest any kind of loop inside any other kind of loop.
It is also possible to nest any number of loops inside each other.
Most of the time one or two loops will be enough to solve a problem, but there is no limit to the number of loops that can work together.