How to use Loops in JavaScript
Loops in JavaScript
The usage of loops to repeat group of instructions many time. Sometimes when you write code, you want the run same block of code a number of times. You can use looping statements in your code..
There are three
types of conditional statements:
1) For Loop
2) while loop
3) do..while loop
For Loop
For loops are used
to do something a set number of times.
The first parameter of "for" is executed the first time and it is
used to initiate the variable of the loop, the second parameter indicates the
condition to be achieved so that the loop will continue executing, and third
parameter is a statement that executes at the end of every iteration and updates
the value of the iteration variable.
Syntax
| for
(initialization; condition; increment) { code to be executed; } |
Example
| <html> <body> <Script Language="JavaScript"> for ($i=1; $i<=10; $i++) { echo "loop values is : ".$i."<br>"; } </script? </body> </html> |
In this example, the looop will run 10 times because you have started initialization from 1($i=1) and conditionis less than or equal to 10 ($i<=10) and this will increment of 1 ($i++):
| loop
values is 1 loop values is 2 loop values is 3 loop values is 4 loop values is 5 loop values is 6 loop values is 7 loop values is 8 loop values is 9 loop values is 10 |
While Loop
While loops are pieces of code which will repeat until the condition is met.
Syntax:
| <Script
Language="JavaScript"> while (condition) { while the condition carries a true value; } </script? |
At the end of each block execution, the while condition is tested again. If the condition holds a true value, the code block will be executed again. Otherwise if the condition holds a false value, the code block will complete its operation.
Example:
| <Script
Language="JavaScript"> test = 0; while (i< 10) { document.write("i is less than 10. <br />"); i++; } </script> |
The above example demonstrates a loop that will continue to run as long as the variable i is less than, or equal to 10. i will increase by 1 each time the loop runs:
Output
| Example
results : 0 is less than 10. 1 is less than 10. 2 is less than 10. 3 is less than 10. 4 is less than 10. 5 is less than 10. 6 is less than 10. 7 is less than 10. 8 is less than 10. 9 is less than 10. |
Do.. while loop
Do..while loops are pieces of code which will repeat until the condition is true. It is opposite of while loop
| <Script
Language="JavaScript"> while (condition) { do this block of coding; while the condition carries a true value; } </script> |
Example
| <Script
Language="JavaScript"> test = 0; while (test < 10) { document.write("test is less than 10. <br />"); test++; } </script> |
The above example will increment the value of test at least once, and it will continue incrementing the variable test while it has a value of less than 10:
