Loops allow us to repeat a block of code, which is an essential concept in programming. There are different types of loops that you will encounter in your journey as a developer and these are for, while, and do-while. Let's look at some examples of each of these loops.
For loop
the for loop is the most popular type of loop. This loop allows a code block to be repeated a predetermined number of times.
For loop syntax
for (initialization; condition; increment/decrement) {
// block of code
}
Let's break the syntax down.
Before the loop begins, the initialization statement is only executed once. It is used to set the loop variable's initial value. Each time the loop iterates, the condition statement is evaluated. The loop continues if the condition is true; if not, it comes to an end. Each time the loop iterates, the increment/decrement statement is executed which changes the loop variable.
Let's look at an example.
for (let i = 0; i < 3; i++) {
console.log("I am a loop");
}
The variable i
is initialized to 0, and at the conclusion of each iteration, i
is increased by 1 if it is less than 3. The loop will run three times, and the console will display "I am a loop" 3 times.
While loop
The while loop is used when you are uncertain of how many times you want to repeat your block of code.
While loop syntax
while (condition) {
// block of code
}
Before each iteration of the loop, the condition statement is evaluated. The loop continues if it is true; otherwise, it is terminated.
Let's look at an easy example.
let i = 0;
while (i <= 4) {
console.log(i);
i++;
}
The variable i
is initialized to 0, and at the end of each iteration, i
is increased by 1 if it is less than or equal to 4. The loop will run 5 times, and the console will display the numbers 0 through 4.
do while loop
The do-while loop is similar to the while loop, the only difference is that, the do-while loop always executes the code block at least once.
do-while syntax
do {
// code block
} while (condition);
The condition statement is evaluated after the block of code has been run. The loop continues if it is true; if not, it comes to an end.
Let's look at an example.
let i = 0;
do {
console.log("I'm a do-while loop");
i++;
} while (i < 3);
This loop will execute the block of code once, then checks if the condition is true. While the condition is true the loop will keep printing to the console "I'm a do-while loop". When the condition evaluates to false, the loop stops executing.
In this example the sentence "I'm a do-while loop" will be printed 3 times before the loop stops executing.
Top comments (0)