While loop in TypeScript

TypeScript is a superset of JavaScript which is strongly typed and provides static typing. This helps in catching errors, making 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 while-loop in TypeScript.

while loop

A while loop keeps executing a code block until a condition is true. The while loop condition is checked before executing the defined code block. When we enter a while-loop, the defined condition is checked. If the condition is true, then the code block is executed. Otherwise, if the condition is evaluated as false, then the while loop breaks.

Syntax

The syntax of the loop is given below:

while (condition){
// Code block
}
While loop syntax

In the above-given syntax, condition is used to define the condition that is checked before each iteration.

The important point to note is that the while loop condition is checked before the code block runs.

Flow chart

The flow chart below shows how the while loop is executed:

Flow chart of while loop's execution
Flow chart of while loop's execution

The flow chart shows that when we enter into the while loop, the condition is checked prior to executing the code block. If the condition is false, then the while loop breaks and the code block is not executed.

Coding example:

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

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

The code explanation is given below:

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

  • Line 2: We define the while loop with the condition that the value of idx should be less than 5 (idx < 5).

  • Line 3: We print a string with the current value of idx plus 1.

  • Line 4: We increment the value of idx by 1.

Conclusion

In conclusion, the while loop helps to excel in scenarios where we need to iterate based on dynamic conditions or perform condition checks before executing a code block.

Learn about do-while loops

Learn about for loops

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved