Code highlights logo

Learn

Loops

The While Loop

The while loop is used to repeatedly execute a block of code as long as a specified condition is true. It is used when the number of iterations is not known beforehand. The basic syntax of the while loop is:

1while (condition) {
2 // code to be executed
3}

The condition is evaluated before each iteration. If the condition is true, the code block inside the loop will execute. If the condition becomes false, the program will exit the loop and continue to the next section of code.

Example:

1let i = 0;
2
3while (i < 5) {
4 console.log("Iteration:", i);
5 i++;
6}

In the example above, the loop will execute as long as i is less than 5. The code block inside the loop will print the value of i and then increment i by 1. This will repeat until i becomes equal to or greater than 5.

It's important to ensure that the condition inside the while loop will eventually become false to avoid infinite loops. An infinite loop is a loop that never exits, causing the program to hang or crash. To prevent this, make sure the condition is properly defined and will eventually evaluate to false.


Instructions

1.

Write a while loop that runs as long as count is less than 5. Inside the loop, increment the value of count by 1.

Sign up to start coding

Already have an account?

Sign In

Course content