Typescript Do While Loop Examples | Javascript

In this blog post, learn to Do while loop examples in typescript and javascript.

Do While Loop in typescript/javascript

Do while loop is the same as a [while loop](/2018/10/typescript-learn-while-loop-examples.html).

While loop executes the condition expression first.

Do while loop executes the condition expression last after the code statement executes.

Do and while are keywords in the typescript. In this do-while loop, Code statements execute at least once.

These loops are used to iterate the iterable objects like set, Map, and Array.

The syntax of Do while loop works the same in typescript and javascript.

Syntax:

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

code block statements are enclosed in open and closed braces and executed at least once.

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

do while loop Example in typescript

The below example prints the number 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 is an example of do while infinite with 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?

The break is a keyword in typescript.

It is used to exit from the do while loop execution.

The further statements after the keyword break 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 exit here for first matched number divided by 3 is zero
  }
  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 used 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);
};

calling the getRecords method which is async, pauses the execution of await until the promise returns a response, and doing the while loop works as expected.

Conclusion

To sum up, We learned the do-while loop in typescript with an example for an infinite loop and how to use the break keyword in this loop.