Typescript do while loop
Created By: chatGPT
A do...while loop in TypeScript allows you to execute a block of code at least once and then repeat it as long as a specified condition is true. This is particularly useful when you need the loop to execute before checking the condition. Here’s the basic syntax:
do {
// code block to be executed
} while (condition);
In the above syntax, the code block will be executed once, and then the condition is evaluated. If the condition is true, the loop will execute again; if it’s false, the loop will terminate.
// Example of a do...while loop
let count = 0;
do {
console.log('Count is: ' + count);
count++;
} while (count < 5);
In this example, we initialize a variable
count
to 0. The do...while
loop will log the current value of count
, increment it, and continue to loop until count
is no longer less than 5. The output will be:// Output:
// Count is: 0
// Count is: 1
// Count is: 2
// Count is: 3
// Count is: 4
If you need to ensure that the code inside the loop runs at least once even when the condition is false upon the first check, a do...while loop is the appropriate choice, unlike a regular
while
loop.// Example of a do...while loop with a false condition
let x = 10;
do {
console.log('This will run at least once.');
x++;
} while (x < 10);