TypeScript While Loop
Learn how to repeat code using the while loop in TypeScript. Understand loop conditions, counter variables, infinite loops, break, continue, and practical examples with expected outputs.
What Will We Learn?
While loops are useful when the number of repetitions depends on a condition rather than a fixed count.
- Understand while loop syntax.
- Check conditions before each iteration.
- Repeat statements using a counter variable.
- Calculate totals using a while loop.
- Understand infinite loops and how to avoid them.
- Use break and continue in while loops.
- Apply while loops in practical examples.
While Loop Workflow
Follow these steps to understand how a while loop executes repeatedly.
Step 1
InitializeSet the initial value.
Step 2
Check ConditionEvaluate true or false.
Step 3
ExecuteRun the loop body.
Step 4
RepeatUpdate the value and check again.
1. While Loop Syntax
A while loop checks its condition before executing the statements inside the loop.
Syntax
while (condition) {
// Statements to execute
}
Important Parts
| Part | Purpose | Example |
|---|---|---|
| Initialization | Sets the starting value before the loop. | let i = 1; |
| Condition | Determines whether another iteration should run. | i <= 5 |
| Loop body | Contains the statements executed during each iteration. | console.log(i); |
| Update | Changes the value so the condition can eventually become false. | i++; |
2. Basic While Loop
A while loop can display a sequence of numbers by increasing a counter during each iteration.
Example
let count: number = 1;
while (count <= 5) {
console.log(count);
count++;
}
Expected Output
1
2
3
4
5
How It Works
- The variable
countstarts at 1. - The condition checks whether
count <= 5. - The current value is displayed.
count++increases the value by one.
When count becomes 6, the condition is false and the loop terminates.
3. When the Condition Is False
If the condition is false before the loop begins, the while loop skips its body completely.
Example
let count: number = 10;
while (count <= 5) {
console.log(count);
count++;
}
console.log("Loop completed");
Expected Output
Loop completed
Since 10 is greater than 5, the condition is false from the beginning. The loop body never executes.
4. While Loop in Descending Order
A while loop can count backward by decreasing the counter during every iteration.
Example
let count: number = 5;
while (count >= 1) {
console.log(count);
count--;
}
Expected Output
5
4
3
2
1
The counter starts at 5 and decreases by one until it reaches 0. At that point, the condition becomes false.
5. Calculate the Sum Using a While Loop
A while loop can calculate a total by repeatedly adding the current counter value to a sum variable.
Example
let count: number = 1;
let sum: number = 0;
while (count <= 5) {
sum += count;
count++;
}
console.log("Sum: " + sum);
Expected Output
Sum: 15
Calculation
sum = 0 + 1;
sum = 1 + 2;
sum = 3 + 3;
sum = 6 + 4;
sum = 10 + 5;
// Final sum = 15
The loop adds every number from 1 to 5. The final total is 15.
6. Loop Through an Array
A while loop can access array elements using an index. The loop continues while the index remains smaller than the array length.
Example
let students: string[] = ["Rahul", "Priya", "Amit"];
let index: number = 0;
while (index < students.length) {
console.log(students[index]);
index++;
}
Expected Output
Rahul
Priya
Amit
The index starts at zero and increases after each iteration. Once it reaches the array length, the loop stops.
7. Using Break in a While Loop
The break statement immediately
terminates the nearest enclosing loop.
Example
let count: number = 1;
while (count <= 10) {
if (count === 4) {
break;
}
console.log(count);
count++;
}
Expected Output
1
2
3
When count becomes 4, the break statement exits the loop before 4 is printed.
8. Using Continue in a While Loop
The continue statement skips the
remaining statements in the current iteration
and begins the next iteration.
Example
let count: number = 0;
while (count < 5) {
count++;
if (count === 3) {
continue;
}
console.log(count);
}
Expected Output
1
2
4
5
The value is incremented before checking continue. When count becomes 3, printing is skipped. The next iteration continues with 4.
9. Infinite While Loop
An infinite loop occurs when the loop condition never becomes false and no statement exits the loop.
Incorrect Example
let count: number = 1;
// Do not run this example as written.
while (count <= 5) {
console.log(count);
// count is never updated.
}
Correct Example
let count: number = 1;
while (count <= 5) {
console.log(count);
count++;
}
Expected Output
1
2
3
4
5
The correct example updates count in each iteration. Eventually, the condition becomes false and the loop ends.
10. While Loop vs For Loop
Both loops repeat code while a condition is true. The main difference is how the initialization, condition, and update are organized.
| Feature | While Loop | For Loop |
|---|---|---|
| Syntax | Condition appears in the while statement. | Initialization, condition, and update are in the header. |
| Best suited for | Condition-based repetition. | Counted repetition or index-based iteration. |
| Counter update | Usually written in the loop body. | Usually written in the loop header. |
| Risk | May be infinite if the condition never changes. | May also be infinite if its condition never changes. |
Same Task Using a For Loop
for (let count: number = 1; count <= 3; count++) {
console.log(count);
}
Same Task Using a While Loop
let count: number = 1;
while (count <= 3) {
console.log(count);
count++;
}
Expected Output for Both
1
2
3
Practical Example: CIIT Student Marks
Let's calculate a student's total and average marks using a while loop.
Example
let studentName: string = "Priya";
let marks: number[] = [80, 75, 90, 85, 70];
let index: number = 0;
let totalMarks: number = 0;
while (index < marks.length) {
totalMarks += marks[index];
index++;
}
let averageMarks = totalMarks / marks.length;
console.log("Student: " + studentName);
console.log("Total Marks: " + totalMarks);
console.log("Average Marks: " + averageMarks);
Expected Output
Student: Priya
Total Marks: 400
Average Marks: 80
The while loop processes each mark, adds it to the total, and advances the index. The final total is divided by the number of subjects to calculate the average.
Common Mistakes
- Forgetting to update the counter variable.
- Using an incorrect condition that never becomes false.
- Accessing an array element outside its valid range.
- Placing continue before a required counter update.
- Assuming a while loop always executes at least once.
- Forgetting that the condition is checked before the loop body.
Practice Task
Create a TypeScript program that performs the following tasks.
- Print numbers from 1 to 10.
- Calculate the sum of numbers from 1 to 10.
- Print all student names from an array.
- Skip the number 5 using continue.
Hint
let count: number = 1;
let sum: number = 0;
while (count <= 10) {
if (count !== 5) {
console.log(count);
}
sum += count;
count++;
}
console.log("Sum: " + sum);
let students: string[] = ["Rahul", "Priya", "Amit"];
let index: number = 0;
while (index < students.length) {
console.log(students[index]);
index++;
}
Expected Output - Sum
Sum: 55
Expected Output - Student Names
Rahul
Priya
Amit
Summary
In this lesson, we learned how while loops work, how conditions control repetition, and how to process arrays and calculate totals using loops. We also covered break, continue, infinite loops, and the difference between while and for loops.
Key Point: A while loop checks its condition before each iteration. Update the relevant values so the loop can eventually stop.