Typescript Do While Loop Examples | Javascript

In this blog post, learn how to use Do While loop examples in TypeScript and JavaScript.

Do While Loop in TypeScript/JavaScript

The Do while loop functions similarly to a while loop.

A While loop evaluates the condition expression first, whereas a Do while loop executes the condition expression last after executing the code statement.

Do and while are keywords in TypeScript. In this do-while loop, code statements execute at least once.

These loops are utilized to iterate through iterable objects such as set, Map, and Array.

The syntax of the Do while loop remains consistent in TypeScript and JavaScript.

Syntax:

do {
  // code block statements
} while (Conditional Expression)

Code block statements are enclosed within opening and closing braces and execute at least once.

If the conditional expression is true, the code block statements are re-executed.

do while loop Example in TypeScript

The following example prints numbers from 1 to 5.

let counter = 1;
do {
  console.log(counter);
  counter++;
} while (counter <= 5);

Output:

1
2
3
4
5

Do-while Infinite loop example

This example demonstrates a do while infinite loop with the conditional expression always set to true.

let counter = 1;
do {
  console.log(counter);
  counter++;
} while (true);

Output:

1
2
Infinite

How to use the Break keyword in the do-while loop?

break is a TypeScript keyword utilized to exit the do while loop execution. Subsequent statements after the break keyword are not executed.

Syntax :

break;

Here is an example

let counter = 1;
do {
  if (counter % 3 === 0) {
    console.log("IF Condition met");
    break; // Do While loop exits here for the first number divisible by 3
  }
  counter++;
  console.log("condition not met");
} while (counter <= 5);

Output:

condition not met
condition not met
IF Condition met

How to use async and await in the do-while loop?

async and await are employed for asynchronous operations.

let’s see an example

const getRecords = async (_) => {
  let isFlag = false;
  do {
    let res = await fetch("/api/get");
    if (res.status === 200) isFlag = true;
  } while (!isFlag);
};

Invoking the getRecords method, which is asynchronous, pauses the execution until the promise returns a response, allowing the while loop to function as anticipated.

Conclusion

In conclusion, we have explored the do-while loop in TypeScript with examples for an infinite loop and how to use the break keyword within this loop.