While and Do/While Loops

Introduction to while loops in JavaScript.

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
Press + to interact
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 ...