While Loop
When you need to repeatedly execute a block of code until a certain condition is met, you can use the while
loop.
For example, using a while
loop can be akin to "waiting for water to boil, and once it does, turning off the heat."
The while loop executes a block of code repeatedly as long as a given condition is true.
while (condition) {
// Code to be executed while the condition is true
}
Example 1: Counting Down
Below is an example of counting down a number by 1 each time as long as the condition number > 0 is true.
let number = 5;
while (number > 0) {
console.log(number);
number--;
}
In this example, console.log(number);
is executed as long as number
is greater than 0, and after each execution, the value of number
is decreased by 1.
Example 2: Managing Budget
Let's represent a scenario where you have $100 in your wallet and you keep buying $20 snacks until your money gets less than $30.
let money = 100; // Initial amount of money in the wallet
let i = 0; // Initial count of snacks bought
// Repeat as long as the money is more than $30
while (money > 30) {
i++; // Count of snacks bought
money -= 20; // Subtract the price of the snack from the wallet
console.log(i + ' time(s) after buying, $' + money + ' left');
}
console.log(`Remaining money: $${money}`);
Important Note on while Loops: Infinite Loops
The most critical thing to watch out for when using a while
loop is avoiding infinite loops.
An infinite loop occurs when the condition always remains true, causing the loop to run endlessly.
Such loops can stop your program from responding or consume excessive system resources.
For example, the following code falls into an infinite loop.
let number = 5;
while (number > 0) {
console.log(number);
// The value of number does not decrease, so the condition is always true
}
To avoid infinite loops, always ensure that within the loop, you modify a variable or component in such a way that the condition will eventually become false. Regularly review and test your code to ensure this.
Want to learn more?
Join CodeFriends Plus membership or enroll in a course to start your journey.