Loops:
For
Loops:For... In
Loops:For... Of
Loops:While
Loops:Do... while
Loops:
Let's go back to the Dogs d'Amour and make an [array]
of their albums:
let dogsAlbums = ["(Un)authorised Bootleg Album", "Dynamite Jet Saloon", "Errol Flynn", "Straight", "More Unchartered Heights Of Disgrace"];
From here, use the for
loop to iterate through those albums (open console to see the results):
With this loop, the second and third conditions are implied. These original conditions (i < variable.length; i++
) are replaced by the word
in
.
For... in
lops are good if we need to retrieve work with the index number of each element in an [array]
.
With this loop, the second and third conditions are implied. These original conditions (i < variable.length; i++
) are replaced by the word
of
.
For... of
loops are good if we need to retrieve and work with the content of an [array]
, as the loop retrieves the
element without needing its index number.
While
loops run code blocks while a condition is true. These original conditions (i < variable.length; i++
) are replaced by the word
of
.
Note that with while
loops, the variable i
needs to be declared, and told where to start from.
Also in the example above, (and as shown in the console), note where the statement "While loop" is situated. This piece of code
is written outside of the loop (here, before the loop), otherwise it will be repeated too.
Because i++
is stated within the loop itself, anything that does not need to be repeated needs to be stated outside of the loop.
Do... while
loops run code blocks once before checking if a condition is true. This means that even if the condition
is false, the code will run once.
What does it mean, that the code block will run once before checking if it is true? Our variable i
is set to 0
above.
From our previous loops, we can see that the Dogs d'Amour released 5 albums. Let's now set i = 6
to see what happens:
We can see in the console that the code has actually run, and it has found that index #6 does not exist.
We can try the same thing with the while loop:
Looking in the console, we can see that the loop for the While loop has not run. All we see is the title "While loop" because this was outside of the loop.
Again, note that with do... while
loops, the variable i
needs to be declared, and told where to start from.
Also in the example above, (and as shown in the console), note where the statement "Do... while loop" is situated. This piece of code
is written outside of the loop (again, here, before the loop), otherwise it will be repeated too.
Because i++
is stated within the loop itself, anything that does not need to be repeated needs to be stated outside of the loop.