There are mainly four types of loops in JavaScript.
for loop
for/in a loop (explained later)
while loop
do…while loop
for loop
Syntax:
for(statement1; statement2; statment3) { lines of code to be executed }
- Statement1 is executed first, even before executing the looping code. So, this statement is normally used to assign values to variables used inside the loop.
- The statement2 is the condition to execute the loop.
- The statement3 is executed every time after the looping code is executed.
<html> <head> <script type="text/javascript"> var students = new Array("John", "Ann", "Aaron", "Edwin", "Elizabeth"); document.write("<b>Using for loops </b><br />"); for (i=0;i<students.length;i++) { document.write(students[i] + "<br />"); } </script> </head> <body> </body> </html>
while loop
Syntax:
while(condition) { lines of code to be executed }
The “while loop” is executed as long as the specified condition is true. Inside the while loop, you should include the statement that will end the loop at some point in time. Otherwise, your loop will never end, and your browser may crash.
do…while loop
Syntax:
<pre> do { block of code to be executed } while (condition)
The do…while loop is very similar to the while loop. The only difference is that in do…while loop, the block of code gets executed once even before checking the condition.
Example:
<html> <head> <script type="text/javascript"> document.write("<b>Using while loops </b><br />"); var i = 0, j = 1, k; document.write("Fibonacci series less than 40<br />"); while(i<40) { document.write(i + "<br />"); k = i+j; i = j; j = k; } </script> </head> <body> </body> </html>