While Loop in JavaScript
In JavaScript, while loops loop through a block of code until the specified condition is true. The condition is evaluated before executing the statement. The syntax of the while loop is very similar to if statement.Syntax while (condition) { // execute this code as long as the condition is true }In the following example, we have to take a variable i = 1, and the while condition is that when it executes it should be less than 5. For each iteration of the loop, we will add one number. Output When we will run the above example, we will receive the following result.
Infinite Loop using While in JavaScript
You might have already the idea what Infinite loop is because of its name. An infinite loop is a loop that will keep running forever. If you make an infinite loop by accident it can crash your browser. So it is really important the awareness of infinite loop otherwise can crash your computer or browser. Look at the example of the infinite loop.// Start a infinite loop while (true) { // execute code forever }
Do While Loop in JavaScript
We have learned upside about while loop. The while loop will run a block of code until the specified condition is true. Do..while statement is slightly different from while statement, it evaluates the condition at the end of each loop irritation. And do...while condition always executes once even if the condition is never true.I am going to show you the same example with do..while loop so you can understand the difference between them. Output In the following example javascript, we have started variable with i = 1. Now it will print the output and increase the value of the variable i by 1. When the condition will be evaluated loop will continue to run until the variable i is less than 5 or equal to 5. In this tutorial, we have learned about while loop and do-while loop and the difference between them. We also discussed the infinite loop and how it can you save yourself from crashing your browser. This is the last tutorial of loop and if you want to learn more about loops like for...loop, for..in loop and for..of loop then go visit for loop in JavaScript. That's it for today, for more content like this that add value to your life. Keep visiting our website. Comment below if you want to ask anything.Syntax
do {
// execute code
} while (condition);