TypeScript While Loop

A TypeScript while loop repeatedly executes a block of statements as long as its condition evaluates to true. It is useful when the number of iterations is not known before the loop starts.

Unlike a TypeScript for loop, a while statement does not have dedicated sections for initializing and updating a control variable. These operations must be written separately when the loop depends on a counter.

The condition is checked before every iteration. If it is initially false, the loop body does not execute. The body must normally perform an operation that can eventually make the condition false; otherwise, the program may enter an infinite loop.

TypeScript While Loop Syntax

Following is the syntax of TypeScript while loop:

</>
Copy
 while(condition) { 
     // set of statements
 }
  • while is the keyword
  • The condition is evaluated and if the result is true, the set of statements are executed. The condition is checked again, and the loop repeats. Whenever the condition evaluates to false, the while loop is broken.

The execution order is condition check, loop body, and then another condition check. TypeScript applies JavaScript truthiness rules to the condition, although an explicit Boolean expression is usually easier to read and maintain.

Example 1 – Simple TypeScript While Loop

Following is a simple while loop iterating for N times.

example.ts

</>
Copy
var N = 4
var i = 0

while(i<N){
    // set of statement in while loop
    console.log(i)

    i++ // updating control variable
}

Output

0
1
2
3

The counter starts at 0. Each iteration prints its current value and increments it. When i reaches 4, the expression i < N becomes false and execution continues after the loop.

Example 2 – Finding a Factorial with a TypeScript While Loop

Following example demonstrates the usage of while loop in finding a factorial of a number.

example.ts

</>
Copy
var N = 6
var i = 1
var factorial = 1

while(i<=N){
    factorial = factorial * i
    i++ // updating control variable
}

console.log("factorial of "+N+" is : "+factorial)

Output

factorial of 6 is : 720

The accumulator begins at 1 and is multiplied by each integer from 1 through 6. The condition uses <= so that the final multiplication by 6 is included.

Using break in a TypeScript While Loop

The break statement ends the nearest loop immediately. It is useful when the stopping condition is discovered inside the loop body, such as when searching an array for a particular value.

</>
Copy
const values: number[] = [12, 18, 25, 31];
let index: number = 0;

while (index < values.length) {
    if (values[index] === 25) {
        console.log(`Found 25 at index ${index}`);
        break;
    }

    index++;
}

Output

Found 25 at index 2

Using continue in a TypeScript While Loop

The continue statement skips the remainder of the current iteration and starts the next condition check. Update the control variable before continue when necessary, or the loop may repeatedly process the same value.

</>
Copy
let number: number = 0;

while (number < 5) {
    number++;

    if (number === 3) {
        continue;
    }

    console.log(number);
}

Output

1
2
4
5

TypeScript while (true) Loop with an Explicit Exit

A while (true) loop intentionally has a condition that never becomes false. It must provide a reliable exit, commonly through break, return, or an exception. This form is appropriate when the exit decision can only be made after work inside the loop.

</>
Copy
let attempts: number = 0;

while (true) {
    attempts++;
    console.log(`Attempt ${attempts}`);

    if (attempts === 3) {
        break;
    }
}

Use this pattern only when the exit path is clear. If the break condition can never be reached, the loop continues indefinitely.

TypeScript While Loop vs For Loop and Do While Loop

LoopCondition checkBest suited to
whileBefore each iterationRepeating while a condition remains true when the iteration count is not known in advance
forBefore each iterationCounter-based iteration with initialization, condition, and update kept together
do...whileAfter each iterationRunning the body at least once before testing the condition

A while loop can execute zero times because its condition is tested first. A do...while loop always executes its body once before checking whether another iteration is required.

Common TypeScript While Loop Errors

  • Missing the counter update: If the condition depends on a counter, failing to change that counter can create an infinite loop.
  • Using the wrong comparison: Choosing < instead of <=, or the reverse, can cause an off-by-one result.
  • Updating before processing: Incrementing a counter at the start of the body may skip the initial value.
  • Placing continue before the update: The update becomes unreachable for that iteration and the condition may never change.
  • Assuming the body runs once: A while loop is skipped entirely when its initial condition is false.

TypeScript While Loop FAQs

When should I use a while loop in TypeScript?

Use a while loop when repetition depends on a changing condition and the number of iterations is not known beforehand. Examples include processing input until it is valid or searching until a matching item is found.

Can a TypeScript while loop execute zero times?

Yes. TypeScript evaluates the condition before entering the loop body. If the condition is false on the first check, the body is skipped.

How do I stop an infinite while loop in TypeScript?

Make sure each iteration moves the program toward a false condition, or provide a reachable break or return statement. If a running program is already stuck in an infinite loop, terminate that process through the terminal or development environment.

Does a TypeScript while loop work differently from JavaScript?

No. TypeScript uses the same runtime while behavior as JavaScript. Type annotations can help verify the values used by the loop, but they do not change how the loop executes.

TypeScript While Loop Editorial QA Checklist

  • Confirm that every loop condition can eventually become false or has a documented exit statement.
  • Check counter boundaries for off-by-one errors, especially when choosing between < and <=.
  • Verify that continue cannot bypass an update required by the loop condition.
  • Run each TypeScript example and compare its console output with the displayed result.
  • Confirm that the selected loop type matches whether the body may run zero times or must run at least once.

TypeScript While Loop Summary

In this TypeScript Tutorial, we have learnt the syntax and usage of while loop with example programs. In our next tutorial, we shall learn about do while loop.