3.7 while Loops
Loops repeat a block of code. A while loop checks a condition first. As long as the condition is true, JavaScript runs the loop body, then goes back and checks the condition again.
Basic while structure
A stable while loop usually has three parts:
- Initial value: prepare the loop variable before the loop starts.
- Condition: decide whether the loop should continue.
- Update: change the loop variable inside the loop.
let i = 1; // initial value
while (i <= 5) { // condition
console.log("In loop: i =", i);
i += 1; // update
}
console.log("After loop: i =", i);Output:
In loop: i = 1
In loop: i = 2
In loop: i = 3
In loop: i = 4
In loop: i = 5
After loop: i = 6A while loop checks before it runs. That means the loop body may run many times, or it may run zero times.
Accumulation and averages
Loops often work with an accumulator variable. The program below computes the average height of five people.
const NUM_PEOPLE = 5;
const heights = [160.8, 175.2, 171.2, 181.3, 164];
let total = 0;
let i = 0;
while (i < NUM_PEOPLE) {
total += heights[i];
i += 1;
}
let average = total / NUM_PEOPLE;
console.log(`Average height: ${average.toFixed(2)}`);Output:
Average height: 170.50total += heights[i] adds the current height into the accumulated total. After the loop ends, total stores the sum of all heights.
Looping until a condition changes
while is useful when the number of repetitions is not known immediately. For example, you can count how many digits an integer has.
let num = Math.abs(Number(prompt("Enter an integer:")));
let digits;
if (num === 0) {
digits = 1;
} else {
digits = 0;
while (num !== 0) {
num = Math.floor(num / 10);
digits += 1;
}
}
console.log("Digits:", digits);The program handles 0 separately. If you only write while (num !== 0), the loop will not run for input 0, and the digit count would incorrectly become 0.