If you want to perform any operation again and again , we can use loop to run over same code.
or Whenever you want to perform operation on list of elements, then you need to loop through .
There are 2 type of while loop:
- While Loop: check the condition, if true, run the block else exit
1 2 3 |
while (condition) { //code to be executed } |
Example Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <p id="div1"></p> <script type="text/javascript"> let text = "" let count = 0; while (count < 5) { text += "<br> number is " + count; count++; } document.getElementById("div1").innerHTML = text; </script> </body> </html> |
number is 0
number is 1
number is 2
number is 3
number is 4
2. Do While Loop: The do-while loop executes the loop body before checking the provided condition.
Syntax:
1 2 3 |
do { //code to be executed } while (condition) |
Example code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <p id="div1"></p> <script type="text/javascript"> let text = "" let count = 0; do { text += "<br> number is " + count; count++; } while (count < 5); document.getElementById("div1").innerHTML = text; </script> </body> </html> |
Output:
number is 0
number is 1
number is 2
number is 3
number is 4