While and Do While Loops in JavaScript

While and Do While Loops in JavaScript

A comprehensive guide with a ton of examples.

ยท

6 min read

A lot of times in JavaScript, we often need to iterate over or through a string of characters, an array, objects, or even precisely repeat a block of code several times.

The JavaScript program that helps us achieve this is known as Loop.

You can think of a loop as simply repeating an action (mostly a block of code) a specified number of times as long as a certain condition is met.

Importance of Loops.

Take for example,the following code:

console.log(0); // 0
console.log(1); // 1
console.log(2); // 2
console.log(3); // 3
console.log(4); // 4

Consider this too:

let n = 0;

while (n<5) {
  n++;
  console.log(n);
}

// output - numbers from 0 - 4

Can you identify the difference?

In the first code block, we are simply printing out numbers from 0 to 4 by manually outputting each number on the console.

This method is slow and repetitive; remember DRY (Don't Repeat Yourself)?

In the second code block, we are also doing the same thing but with much fewer codes, and we are also doing it quicker and faster.

Do not worry about understanding the code; we will get back to it later.

Now imagine if you had to print out numbers from 0 to 100. Which method would you choose?Would you manually output each number from 0 to 100 to the console? or would you use Loops?

I guess the answer is obvious.

So,the point here is that JavaScript loops offer a speedier and simpler way to repeatedly execute something, in this case print out numbers.Loops also reduce the amount of time it takes to perform a task in JavaScript.

Now that you are aware of the importance of loops, let's learn more.

Types of Loops in JavaScript.

There are different types of Loops in JavaScript but they all do the same thing - repeat a code block as long as a certain condition is true.

Different loop styles or methods are better to use in certain situations, while others are not.

Depending on you and the circumstances, You may find that one loop strategy is better suited to your needs than another.

The following are loop styles provided in JavaScript.

1.while loops

2. do/while loops

3. for loops

4. for of loop.

5. for in loop.

We will only cover the the while and do while loops in this article.

Let's GOOOO ๐Ÿš€

While Loops.

Syntax:

while(condition){

// execute code

}

The while loop execute or run a statement as long as a given condition is true,once the condition is no longer met again,that is,the condition is false,the while loop terminates and stops executing.

The condition is checked before the statement executes. If the condition is true, the statement gets executed again and the process continues until the condition turns false and the loop stops executing.

Ensure that any condition you have specified will finally return false, otherwise, you will be stuck in what we call an infinite loop-we will discuss more on this later - and you may have to restart your browser again.

Now, this might still sounds unclear, let's better understand with examples.

While Loops Examples.

Consider the following code block:

let n = 0;

while (n<5) {
  n++;
  console.log(n);
}

// output - numbers from 0 - 4

In the above example, the while loop will keep running as long as n is less than 5 which is our condition. The console.log(n) statement inside the loop will print the value of n to the console, and then the n++ statement will increment the value of n by 1.

This allows us to print different values on each iteration and hence the output.

Now , let's move onto the next!

Do While Loops.

Do while loops are basically the same as while loops but with a major difference:the code block will be executed at least once before a condition is checked, even if the condition is false.

Remember,in a while loop,a statement gets executed only if a condition is true but in a do while loop,the code block gets executed at least once even if the condition is false.

This might still sounds vague, let's dive into some examples to get a better understanding.

Syntax:

do {

// execute code

} 

while (condition);

The above syntax is pretty self explanatory.

it says that the block of code inside the loop is executed first, that is,do something first (execute a code block), then check if the condition is true. If it is true, the loop continues to execute, and if it's false, the loop terminates.

Now this is all just syntax, let's practice with a real example.

We will use the same code block we used in while loops but with a small difference.

let n = 0;

do{

console.log(n);

n++;

}

while (n<5);

// output - numbers from 0 - 4

In the above example, the do-while loop will print the value of n to the console first(which is the main difference from the while loop),then increment the value of n by 1, and then check if n is less than 5. If n is less than 5, the loop will continue to execute, otherwise,the loop terminates.

A typical example.

Consider this code block:

let n = 6;

do{
console.log(n);
n++;
}
while (n<5);

// output - 6

In the above example,the do-while loop will print the value of n to the console,which is 6,then increment the value of n by 1 to make 7 but checking the condition,7 is more than 5,which renders the condition false and the loop terminates.

But note that 6 is still printed to the console because the do code block was executed before the condition was checked,hence the reason.

If it were a while loop, there will be no output to the console because a while loop checks if a condition is true before executing a code block,and since 6 is greater than 5,the condition becomes false and no output is returned.

Infinite Loops.

The condition in a normal while or do while loop has been constructed so that it will turn false at a specific point in time as in our previous examples.

If a loop's condition is always true, an infinite loop will result. When this happens, your browser may freeze and you may need to restart because the loop will run indefinitely.

Consider the following code block:

const myName = "Adam";
do {
   // body of loop
} while(myName == "Adam")

Since myName will always be Adam,that means the condition will always be true,hence resulting in an infinite Loop.

Conclusion.

I believe you now have a good grasp of while and do while loops and can now differentiate between them.

Keep practicing and experimenting with loops in your code to become more familiar with them.

Happy coding :)

ย