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.
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.
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 20 snacks until your funds drop below $30.
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.
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.
What is the most appropriate word to fill in the blank?
Lecture
AI Tutor
Design
Upload
Notes
Favorites
Help
Code Editor
Execution Result