While, do and for loop in JavaScript

Kamran Namazov
3 min readJul 25, 2020

--

If you have just started to learn JavaScript, be sure that you will need to meet ‘loop’ concept. So how you can loop any action and why you need to use it.

Do not worry, I will explain it in simple words, so take your coffee and continue to read from below(i’m just joking, it’s not too long to read, you can read it without coffee as well:)).

First of all, let’s make it clear first why you need to learn loop as a fundamental.

I have searched the picture for this concept over the internet in order to help you to remind the main concept. I’m pretty sure that any appropriate picture helps to understand the concept better. That’s the picture below for loop concept.

But i know that it’s not the best picture for this concept:). But it’s okay. So in programming you will always need to repeat any action. As you want be clean code writer and don’t want to write hundreds of line for every action, ‘Loop’ concept will make it easy for you. There is an incrementing numbers in the picture above. First comes the integer 1, then it increments by one till….

As we said loops are a way to repeat the same code multiple times. Now i will tell you how to do it by writing code in three ways:

While loop

Let’s start with simple syntax:

while (condition) {
// write your code
// "loop body"
}

Explanation the syntax above is that while the condition is true within the parenthesis the code from the loop body will be executed.

For instance, the loop below outputs i while i < 5:

let i = 0;
while (i < 5) { // it shows from 0 to 4
alert( i );
i++;
}

I have condition i<5, first variable is 0 and i increments by one starting from 0 till 4. There you have it.

The “do while loop”

It’s almost the same thing, but a little bit different syntax is used:

do {
// loop body
} while (condition);

The do/while statement normally creates a loop that executes a block of code once, but check the condition is true after, as a next step, repeats the loop as long as the condition is true. This is the main difference.

See the example below:

let i = 0;
do {
alert(i);
i++;
}
while (i < 5);

The for loop

Most commonly used way that i prefer as well. What happens here? We get the same result, but the cleaner syntax is used than other once.

for (start; condition; step) {
// loop body
}

I just want to provide example below:

for (let i = 0; i < 5; i++) { //it will  show from 0 to 4
alert(i);
}

As shown on the body , you will get the alert again and again while the condition(i<5) is true.

This statement loops through a block of code a number of times.

Let’s finish the article and practice the thing you have learned on this website.

--

--