Member-only story
Loops in Javascript: for loop, while loop, do…while, for…of and for…in
In JavaScript, loops are used to execute the same block of code a specified number of times or until a certain condition is met. There are several types of loops in JavaScript, each with its own specific use case.
for loop
The most basic loop in JavaScript is the for loop. It consists of a starting condition, a stop condition, and a counter. The for loop is often used when you know the exact number of times you want the code to run. Here is an example of a for loop that prints the numbers 1 through 5:
for (let i = 1; i <= 5; i++) {
console.log(i);
}while loop
Another common loop in JavaScript is the while loop. This loop will continue to run as long as a certain condition is true. Here is an example of a while loop that prints the numbers 1 through 5:
let i = 1;
while (i <= 5) {
console.log(i);
i++;
}do…while
The do...while loop is similar to the while loop, but it guarantees that the code inside the loop will run at least once. This is because the condition is checked at the end of the loop instead of at the beginning. Here is an example of a do...while loop that prints the numbers 1 through 5:






