Skip to main content
Practice

While Loop

The while loop is used to repeatedly execute a block of code until a certain condition is met.

For example, you might use a while loop to represent a situation like "waiting for water to boil and then turning off the heat once it does."

A while loop continues to execute the code block as long as the specified condition is true.


Structure of a while loop
while (condition) {
// Code to execute as long as the condition is true
}

Example 1: Counting Numbers

Below is a code example that decrements the variable number by 1 and counts the numbers down as long as the condition number > 0 is true.

Print numbers from 5 to 1
let number = 5;

while (number > 0) {
console.log(number);
number--;
}

In this example, console.log(number); runs while number is greater than 0, and then the value of number is decreased by 1.


Example 2: Budget Management

Let's use code to depict a scenario where you have 100inyourwalletandcontinuetobuy100 in your wallet and continue to buy 20 snacks until your funds drop below $30.

Snack purchase code
let money = 100; // Initial amount in the wallet
let i = 0; // Initial count of snacks bought

// Repeat only while the money is $30 or more
while (money >= 30) {
i++; // Increment snack count
money -= 20; // Deduct snack price from wallet
console.log('After purchasing ' + i + ' time(s), ' + money + ' dollars left');
}

console.log(`Remaining money: ${money} dollars`);

Caution with while loops: Infinite Loops

One of the key concerns when using a while loop is avoiding falling into an infinite loop.

An infinite loop occurs when the condition is always true, and thus the loop never stops.

Such infinite loops can cause the program to hang or excessively consume system resources.

For example, the following code results in an infinite loop.

Infinite loop example
let number = 5;

while (number > 0) {
console.log(number);
// The value of number never decreases, so the condition is always true
}

To avoid infinite loops, always ensure that the loop has a condition that will eventually become false by reviewing and testing the loop's code.

Want to learn more?

Join CodeFriends Plus membership or enroll in a course to start your journey.