Javscript Loops Tutorials - For Loop and While Loops

JavaScript For Loops?


In JavaScript for loop are used when you know in advance how many times the script or a piece of code should be executed. Loops help to remove situations where you have to enter the same piece of code multiple times. Loops will execute a specified number of times or while a specified condition is true.

Sample Pseudo Code:

for (var=startvalue;var<=endvalue;var=var+increment) 
{
    code to be executed
}

The example below defines a loop that starts with i=0. The loop will continue to run as long as i is less than, or equal to 10, i will increase by 1 each time the loop runs.


Example:

<html>
<body>
<script type="text/javascript">
var i=0
for (i=0;i<=10;i++)
{
document.write("The number is " + i)
document.write("<br />")
}
</script>
</table>
</body>
</html>

The output above would be

The number is 0

The number is 1

The number is 2

Etc etc etc


The number is 9 – nine is the last number to be oututed because I has to be less than 10.

While Loop

The JavaScript while loop is much simpler than the for loop. It consists of a condition and the statement block.

Pseudo Code:


while (condition)
   {
   ...statements...
   }


As long as the condition evaluates to 'true', the program execution will continues to loop through the statements.

Example


<html>
<body>
<script type="text/javascript">
var x = 1;
while (x <= 10)
   {
   document.write("The number is " + x)
   x++;
   }
</script>
</table>
</body>
</html>


The output here is the same as for the FOR loop with 9 being the last number outputted.

javascript tutorials