Thursday, October 4, 2018

Typescript Do While Loop Examples | Javascript Do while loop examples

In this blog post, We are going to learn Do while loop examples in typescript and javascript.
Do While Loop Examples in typescript, javascript

Do While Loop in typescript/javascript

Do while loop is same as like a while loop. While loop executes the condition expression first, Do while loop executes the condition expression last after code statements execute Do while are keywords in typescript. In this do while loop, Code statements are executed at least once

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

Syntax

do{
// code block statements
}
while(Conditional Expression)
code block statements are enclosed in open and closed braces and executes at least once. If the conditional expression is true, code block statements re executes

Simple Example 

The below example prints the number from 1 to 5.
let counter=1; 
do {
    console.log(counter)
    counter++;

}
while (counter <= 5) 
Output is
1
2
3
4
5

Infinite example 

This is an example for do while infinite with conditional expression always is set to true.

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

}
while (true) 
Output is
1
2
---- 
Infinite 

Break keyword example

The break is a keyword in typescript. It is used to exit from do while loop execution. The further statements after keyword break are not executed. Syntax :

break;

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 is
condition not met
condition not met
IF Condition met

Related article


EmoticonEmoticon