while Loop
Learn while Loop
A while loop repeats as long as its condition remains truthy, checking before every iteration.
In this lesson, you will study the rule, run a complete TypeScript example, explain its output, and test a small change.
What you’ll learn
- Explain the main rule behind while loop.
- Predict the result of the complete runnable TypeScript example.
- Recognize one common mistake and correct it.
Understand the concept
The while form works well when you do not know the exact iteration count in advance. If the condition starts false, the body does not run. The body must usually update the state that determines whether the loop can finish.
See the concept visually
Use the diagram to locate the checks, values or branches involved in the example.
Run a complete TypeScript example
Save this code as main.ts or paste it into the TypeScript Playground. The example uses fixed values so it runs without prompting for input.
TypeScript code
let remaining: number = 3;
while (remaining > 0) {
console.log(remaining);
remaining--;
}
console.log("Done");Verified output
3
2
1
DoneHow to run locally: npx tsc --strict --target es2022 --module commonjs main.ts, then node main.js. When using a project configuration, run the matching project build instead.
Trace the execution
remaining starts at 3 and decreases after each print. When it reaches 0, the next condition check fails and the loop ends.
Predict the output before you run the sample. Compare each line with the source expression that produced it, and distinguish the type checker’s work from what happens in JavaScript at runtime.
Common mistakes and how to avoid them
If remaining never changes, the loop may not terminate. Use a clear progress variable or an explicit exit condition.
Debugging habit: when a change is rejected, read the exact compiler diagnostic and inspect the operand types. When it compiles but behaves unexpectedly, follow the values through the JavaScript expressions.
Practice it yourself
Change remaining to 0 and verify that only Done prints. Try increasing the start to 5.
Challenge: write down your prediction first, run the changed source, and explain any difference. Return to the verified version before continuing.
Check your understanding
Review the key idea
while Loop: The while form works well when you do not know the exact iteration count in advance.
while is a pre-test loop.
Before continuing, be able to explain what is checked before execution and what actually changes at runtime in the example above.
Reaching the recap and completing the quizzes are separate milestones.