JavaScript For Loop of
Loops can execute a block of code as long as a specified condition is true.
The While Loop
The while loop loops through a block of code as long as a specified condition is true
Example
<!DOCTYPE html> <html> <body> <h2>JavaScript While Loop</h2> <p id="demo"></p> <script> // Initialize an empty string 'text' let text = ""; // Initialize a variable 'i' with the value 0 let i = 0; // While loop that iterates while 'i' is less than 10 while (i < 10) { // Concatenate the current value of 'i' to the 'text' string text += "<br>The number is " + i; // Increment the value of 'i' i++; } // Display the result in the paragraph with id "demo" document.getElementById("demo").innerHTML = text; </script> </body> </html>You can click on above box to edit the code and run again.
Output
The Do While Loop
The do while loop is a variant of the while loop. This loop will execute the code block once, before checking if the condition is true, then it will repeat the loop as long as the condition is true.
Example
do { // code block to be executed } while (condition);
Example
<!DOCTYPE html> <html> <body> <h2>JavaScript Do While Loop</h2> <p id="demo"></p> <script> // Initialize an empty string 'text' let text = ""; // Initialize a variable 'i' with the value 0 let i = 0; // Do...while loop that iterates at least once and continues while 'i' is less than 10 do { // Concatenate the current value of 'i' to the 'text' string text += "<br>The number is " + i; // Increment the value of 'i' i++; } while (i < 10);You can click on above box to edit the code and run again.
// Display the result in the paragraph with id "demo" document.getElementById("demo").innerHTML = text;
</script> </body> </html>