Javascript-Lesson 6

More loops

The 'while' loop

The 'while' loop runs while some condition is true. Hopefully the code to be executed in the loop will, at some time, cause that condition to become false. Otherwise you will have a never-ending loop! Here is a look at a 'while' loop:
while (some comparison is true)
{

the code to be executed, which should include code to falsify the comparison
}
Note that if the comparison is already false then the code is not executed and the script passes through the loop without executing it at all.

The 'do...while' loop

The 'do...while' loop is tested at the end of the loop, like this:
do
{

code to be executed
}
while (
some condition is true);
Note that the 'do...while' loop code is executed at least once even if the comparison is false.

'break' and 'continue'

Sometimes you may want to finish a loop in the middle without executing the remainder of the code. Using the 'break' command after some comparison in the middle of a loop does just that.

The 'continue' command, on the other hand, after some comparison, skips the remaining code in the loop and goes to the next loop. You must remember that the code to attain the exit condition is not in the code after the 'continue' command or the loop will become never-ending.

Arrays

An array is a list of numbers or texts. When it is declared, it is followed by brackets containing a number one less than the number of items it can hold. You see the first item is always numbered zero.

That is a one dimensional array. A two-dimensional array is declared with two numbers in the brackets. An n-dimensional array is declared with n numbers in the brrackets.

The 'for...in' loop

The reason for mentioning arrays is that the 'for...in' loop is used with arrays. E.G.

<script type="text/javascript">
var x;
var mytools = new Array(2);
mytools[0] = "hammer";
mytools[1] = "drill";
mytools[2] = "screwdriver";

for (x in mytools)
{
document.write(mytools[x] + "<br />");
}
</script>

gives:
hammer
drill
screwdriver
Previous Lesson previous lesson next lesson Next Lesson