For, While and Do While LOOP in JavaScript (With Example)
For, While and Do While LOOP in JavaScript (With Example)
For, While and Do While LOOP in JavaScript (With Example)
https://www.guru99.com/how-to-use-loops-in-javascript.html 1/4
7/24/2021 For, While and Do While LOOP in JavaScript (with Example)
1. for loop
2. for/in a loop (explained later)
3. while loop
4. do…while loop
for loop
Syntax:
1. The statement1 is executed first even before executing the looping code. So, this
statement is normally used to assign values to variables that will be used inside the
loop.
2. The statement2 is the condition to execute the loop.
3. The statement3 is executed every time after the looping code is executed.
1 <html>
2 <head>
3 <script type="text/javascript">
4 var students = new Array("John", "Ann", "Aaron", "Edwin", "Elizabe
5 document.write("<b>Using for loops </b><br />");
6 for (i=0;i<students.length;i++)
7 {
8 document.write(students[i] + "<br />");
9 }
10 </script>
11 </head>
12 <body>
13 </body>
14 </html>
Run
while loop
https://www.guru99.com/how-to-use-loops-in-javascript.html 2/4
7/24/2021 For, While and Do While LOOP in JavaScript (with Example)
Syntax:
while(condition)
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 of time.
Otherwise, your loop will never end and your browser may crash.
1 <html>
2 <head>
3 <script type="text/javascript">
4 document.write("<b>Using while loops </b><br />");
5 var i = 0, j = 1, k;
6 document.write("Fibonacci series less than 40<br />");
7 while(i<40)
8 {
9 document.write(i + "<br />");
10 k = i+j;
11 i = j;
12 j = k;
13 }
14 </script>
15 </head>
16 <body>
17 </body>
18 </html>
Run
do…while loop
Syntax:
https://www.guru99.com/how-to-use-loops-in-javascript.html 3/4
7/24/2021 For, While and Do While LOOP in JavaScript (with Example)
do
} while (condition)
The do…while loop is very similar to while loop. The only difference is that in do…while
loop, the block of code gets executed once even before checking the condition.
1 <html>
2 <head>
3 <script type="text/javascript">
4 document.write("<b>Using do...while loops </b><br />");
5 var i = 2;
6 document.write("Even numbers less than 20<br />");
7 do
8 {
9 document.write(i + "<br />");
10 i = i + 2;
11 }while(i<20)
12 </script>
13 </head>
14 <body>
15 </body>
16 </html>
Run
https://www.guru99.com/how-to-use-loops-in-javascript.html 4/4