Essential JavaScript
Introduction
JavaScript Basics
Numbers
Strings
Logic
Variables
Loops
Objects
Arrays
Going Further
Essential JavaScript
Introduction
JavaScript Basics
Numbers
Strings
Logic
Variables
Loops
Objects
Arrays
Going Further
Nested Loops
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.
Learning Goals
I can create a nested
for
loop in JavaScriptI know how control flows in a nested
for
loopI know the best practice for naming variables in nested
for
loops
Code Editor
Click "Run Code" to execute your JavaScript in a secure sandbox and see the output below.
Console Output
0 output lines