do while Loop in TypeScript

TypeScript is a superset of JavaScript. It provides static typing which means that it is strongly typed and helps in catching errors. This makes it ideal for large team collaborations. Being a programming language, TypeScript provides loops to iterate through a collection of items or execute a block of code multiple times. In this Answer, we will explore the implementation of do-while loop in TypeScript.

do-while

The do-while loop executes a code multiple times until the defined condition is true. Unlike the while loop, the condition for do-while loop is defined at the end of the loop. On the first iteration of the loop, the code block runs first and then the condition is checked. For the rest of the iterations, the block of code runs only if the condition is true.

Syntax

The syntax for the do-while loop is given below:

do{
//Code Block
}
while (condition);
Syntax of do-while loop

In the syntax above, do block contains the code block that is executed in each iteration. The while block contains the condition that is checked once the do block has been executed.

Flow chart

The flow chart below shows how do-while loop executes:

Flow chart of do-while loop
Flow chart of do-while loop

The flow chart show that once we enter the do-while loop, the code block is executed first. Once the code block execution is completed, the condition defined in the while block is checked. If the condition is met, the code block is executed again. If the condition is false, then the do-while loop breaks.

Coding example

Until now, we have gained the understanding that a do-while loop is used to execute a code block until a condition is met. Now we will see an example of using do-while loop in TypeScript:

var idx = 0;
do {
console.log("While loop iteration: " + String(idx+1));
idx++;
}
while (idx < 5)

The code explanation is given below:

  • Line 1: We create a variable idx with value 0.

  • Line 2–5: We define the do block with the code we want to execute until the loop continues.

  • Line 6: We define the condition in the parenthesis () followed by the while keyword.

Conclusion

In conclusion, the do-while loop is similar to the while loop, but the only difference is that the while loop's condition is checked before the code block executes, while in the case of do-while loop, the condition is checked after the code block executes.

Learn about while loops

Learn about for loops

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved