Loops can execute a block of code a number of times.
The for loop is often the tool you will use when you want to create a loop.
for (initialization; test condition; iteration statement){ Statement(s) to be executed if test condition is true }
<script type="text/javascript"> for (i=1; i<=5; i++) { document.write(2 +" * " + i + " = " + 2*i + "<br>") } </script>
2 * 1 = 2 2 * 2 = 4 2 * 3 = 6 2 * 4 = 8 2 * 5 = 10
The JavaScript for/in statement loops through the properties of an object.
for (variablename in object) { statement or block to execute }
<script type="text/javascript"> var student = { stud1:"Ashwani", stud2:"Sachin"}; var names = "" var a; for (a in student) { names += student[a]+ " / "; } document.write(names); </script>
Ashwani Sachin
The while loop loops through a block of code as long as a specified condition is true.
while (condition) { code to be executed }
<script type="text/javascript"> var i = 1; while (i < = 5) { document.write(i + "<br>"); i++; } </script>
1 2 3 4 5
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.
do { code to be executed } while (condition);
<script type="text/javascript"> var i=15; do { document.write(i + "<br/>"); i++; } while (i<=20); </script>
15 16 17 18 19 20