Search⌘ K

While and Do/While Loops

Explore the implementation and difference between while and do while loops in JavaScript. Learn how these loops execute instructions based on conditions and discover practical examples to understand when to use each loop type effectively in your code.

We'll cover the following...

In this lesson, we will how to learn to implement while loops and do/while loops.

while loops

while loops continue to execute a set of instructions while the condition is set to true.

Here, a loop starts with a while token, followed by a condition in parenthesis, and concludes with a set of instructions encapsulated within the brackets.

Let’s write a small program that will count to five in a while loop.

svg viewer
Node.js
var count = 0; // assign 0 to variable count
while (count < 5){
console.log("count",++count); // increment then print count
}
console.log("Program has ended with count:", count);

In the above program, we initialize the variable count by assigning it to 0. Our loop is set to keep running while the count variable ...