Sitemap
Damion Davy

Damion Davy

Passionate about technology — Mobile, Web and Data Science. Always experimenting — solving problems.

Member-only story

Loops in Javascript: for loop, while loop, do…while, for…of and for…in

2 min readDec 7, 2022

--

Press enter or click to view image in full size
Photo by Henry & Co. on Unsplash

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:

--

--

Damion Davy
Damion Davy

Written by Damion Davy

Passionate about technology — Mobile, Web and Data Science. Always experimenting — solving problems.