Thursday, October 4, 2018

Typescript - Learn while loop examples

In this tutorial, We are going to learn while loop in typescript with examples.
typescript while loop example

While loop  Introduction

As every programming language provides while loop. 
While loop executes the statements of code block for true condition expression.
First It evaluates the conditional expressions if it is true, the Code block is executed. else while a block of code is skipped
while is a keyword in typescript. While Loop used for iteration of a collection of objects or arrays

Syntax

while (COnditional Expression){
Code block statements
}

Simple Finite example

This iterates the loop for 5 times and output counter to console log
let counter=1; 
while(counter<=5) {  
    console.log(counter);
    counter++;  
}
Output is
1
2
3
4
5

Break Statement example

Break keyword is used to exit from while loop execution. This will be used when some conditional expression is true
Syntax

break;
let counter=1; 
while (counter <= 6) {  
    if (counter % 3 == 0) {
        console.log("IF Condition met")
        break  //While loop exit here for first matched number divided by 3 is zero
    }
    counter++;  
}
Output is
IF Condition met

Infinite Example 

an infinite loop will be executed when the Conditional expression is configured with true

    while(true){  
        console.log("Infinite loop");  
    }  
 
Output is
Infinite loop
Infinite loop
....
Infinite loop

Related article


EmoticonEmoticon