JavaScript while Loops: Condition-Controlled Repetition
Quick answer
A while loop repeats while its test is truthy. It is useful when the number of repetitions depends on changing state rather than a fixed count.
How it works
Write while (condition) { ... }. The test runs before each body execution, so the body can run zero times. Identify the state that makes the test eventually false. In the example, repeatedly halving a positive even value reaches the threshold; the exercise bounds inputs to guarantee progress.
let remaining = 3;while (remaining > 0) { console.log(remaining); remaining--; }console.log("done");Expected output in Node.js:
321doneDecrement moves remaining toward zero.
let size = 64;let steps = 0;while (size > 8) { size /= 2; steps++; }console.log(size, steps);Expected output in Node.js:
8 3Three halvings reach the threshold.
Common mistakes
An unchanged true condition may cause an infinite loop. Verify progress for all allowed inputs, including the case in which the first test is false.
Practice
Count how many times a positive integer must be divided by two to reach 1 or below.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
JavaScript while Loops: Condition-Controlled Repetition — Knowledge Check
Apply the taught concept and reason about the result.
When does while evaluate its continuation condition?
What happens when the initial while test is false?
How many halvings take 64 down to 8?
Which problem can prevent a while loop from terminating?
When is while often a natural choice?