DEV Community

Cover image for JavaScript - Loops and iteration
Zouhair Sahtout
Zouhair Sahtout

Posted on

JavaScript - Loops and iteration

Loops offer a quick and easy way to do something repeatedly and for loop and if else statement are one of the other control structure.

Control Structures are just a way to specify flow of control in programs.
Any algorithm or program can be more clear and understood if they use
self-contained modules called as logic or control structures.
It basically analyzes and chooses in which direction a program flows
based on certain parameters or conditions.


Image descriptionUse let variable because this counter will later be updated it by for loop
for loop keeps running while the condition rep <= 10; is TRUE
It verifies the condition first rep <= 10;


Example:
for loop and its practical application.
Image description


Now let's learn about two important statements: continue and break

continue: is to exit the current iteration of the loop,
and continue to the next one.

Let's say we want to only log strings to the console.

Image description

break : is used to completely terminate the whole loop.
Let's say I want to stop logging, after I find the first number

Image description


Looping backwards and Nested loops

Image description

We are gonna loop over this array backwards: 3, 2, 1, 0
Image description

We are gonna create a nested loop
Image description


The while loop

Whenever you do need a loop without a counter variable
You can reach out to for the while loop

Basically that happens, when you do NOT know beforehand how many

iteration the loop will have, in your program.

All the while loop what really needs, is the condition.
In this example it's while(rep <= 10)

and that condition, can be any condition, it does NOT have to be related to any counter at all.
Image description


Small game with while loop
Image description

Top comments (0)